发现python3中的字符串中有一个表情符号 [英] Find there is an emoji in a string in python3

查看:0
本文介绍了发现python3中的字符串中有一个表情符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Python3检查一个字符串是否只包含一个表情符号。 例如,有一个is_emoji函数用于检查字符串是否只有一个表情符号。

def is_emoji(s):
    pass

is_emoji("😘") #True
is_emoji("😘◼️") #False

我尝试使用正则表达式,但表情符号没有固定长度。例如:

print(len("◼️".encode("utf-8"))) # 6 
print(len("😘".encode("utf-8"))) # 4

推荐答案

这可以在Python3中运行:

def is_emoji(s):
    emojis = "😘◼️" # add more emojis here
    count = 0
    for emoji in emojis:
        count += s.count(emoji)
        if count > 1:
            return False
    return bool(count)

测试:

>>> is_emoji("😘")
True
>>> is_emoji('◼')
True
>>> is_emoji("😘◼️")
False

与Dunes的答案相结合,避免输入所有表情符号:

from emoji import UNICODE_EMOJI

def is_emoji(s):
    count = 0
    for emoji in UNICODE_EMOJI:
        count += s.count(emoji)
        if count > 1:
            return False
    return bool(count)

这并不是很快,因为UNICODE_EMOJI包含近1330个项目,但它可以正常工作。

这篇关于发现python3中的字符串中有一个表情符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆