Python如何从字符串中提取文本和emoji,代码无法识别emoji如何解决?
问题根因
- emoji库API版本不兼容:你使用的
emoji.UNICODE_EMOJI是v1.x版本的写法,目前主流v2.x以上版本的emoji库将该属性调整为了按语言分类的字典结构,直接判断字符是否在emoji.UNICODE_EMOJI中会永远返回False,这是emoji_list为空的核心原因。 - 部分emoji的变体匹配问题:部分带变体修饰符的emoji直接匹配集合会有遗漏,用库内置的判断方法兼容性更强。
修复方案
直接用emoji库内置的is_emoji()方法判断字符是否为emoji,无需手动查集合,兼容性更好。修正后的完整代码如下:
import emoji text = "#samplesenti @emojitweets i ❤❤❤ sentiment " analysis " http://senti.com/pic_01.jpg " def extract_text_and_emoji(text=text): global allchars, emoji_list # remove all tagging and links, not need for sentiments remove_keys = ('@', 'http://', '&', '#') clean_text = ' '.join(txt for txt in text.split() if not txt.startswith(remove_keys)) # setup the input, get the characters and the emoji lists allchars = [s for s in text] # 替换为内置方法判断emoji emoji_list = [c for c in allchars if emoji.is_emoji(c)] # extract text clean_text = ' '.join([s for s in clean_text.split() if not any(i in s for i in emoji_list)]) # extract emoji clean_emoji = ''.join([s for s in text.split() if any(i in s for i in emoji_list)]) return (clean_text, clean_emoji) allchars, emoji_list = 0, 0 (clean_text, clean_emoji) = extract_text_and_emoji() print('\nAll Char:', allchars) print('\nAll Emoji:', emoji_list) print('\n', clean_text) print('\n', clean_emoji)
效果验证
运行修正后的代码,输出结果和你预期的完全一致:
All Char: ['#', 's', 'a', 'm', 'p', 'l', 'e', 's', 'e', 'n', 't', 'i', ' ', '@', 'e', 'm', 'o', 'j', 'i', 't', 'w', 'e', 'e', 't', 's', ' ', 'i', ' ', '❤', '❤', '❤', ' ', 's', 'e', 'n', 't', 'i', 'm', 'e', 'n', 't', ' ', '&', 'q', 'u', 'o', 't', ';', ' ', 'a', 'n', 'a', 'l', 'y', 's', 'i', 's', ' ', '&', 'q', 'u', 'o', 't', ';', ' ', 'h', 't', 't', 'p', ':', '/', '/', 's', 'e', 'n', 't', 'i', '.', 'c', 'o', 'm', '/', 'p', 'i', 'c', '_', '0', '1', '.', 'j', 'p', 'g', ' '] All Emoji: ['❤', '❤', '❤'] i sentiment analysis ❤❤❤
内容的提问来源于stack exchange,提问作者Tayshawn Hill
相关产品推荐
相关产品推荐

