如何在python中构建规则的表情符号词汇表?
我在一个纯文本文件如何在python中构建规则的表情符号词汇表?,python,regex,python-2.7,python-unicode,Python,Regex,Python 2.7,Python Unicode,我在一个纯文本文件UTF32.red.code中有一个表情符号代码列表。文件的普通内容是 \U0001F600 \U0001F601 \U0001F602 \U0001F603 \U0001F604 \U0001F605 \U0001F606 \U0001F609 \U0001F60A \U0001F60B 基于,我的想法是从文件的内容创建正则表达式,以便捕捉表情。这是我的最小工作示例 import re with open('UTF32.red.codes','r') as emof:
UTF32.red.code
中有一个表情符号代码列表。文件的普通内容是
\U0001F600
\U0001F601
\U0001F602
\U0001F603
\U0001F604
\U0001F605
\U0001F606
\U0001F609
\U0001F60A
\U0001F60B
基于,我的想法是从文件的内容创建正则表达式,以便捕捉表情。这是我的最小工作示例
import re
with open('UTF32.red.codes','r') as emof:
codes = [emo.strip() for emo in emof]
emojis = re.compile(u"(%s)" % "|".join(codes))
string = u'string to check \U0001F601'
found = emojis.findall(string)
print found
找到的
始终为空。我错在哪里?我正在使用Python2.7您的代码在Python3中运行良好(只需将print found
修复为print(found)
)。然而,在Python2.7中,它无法工作,因为它的re
模块有一个已知的bug(请参阅和)
import re
with open('UTF32.red.codes','rb') as emof:
codes = [emo.decode('unicode-escape').strip() for emo in emof]
emojis = re.compile(u"(%s)" % "|".join(map(re.escape,codes)))
search = ur'string to check \U0001F601'
found = emojis.findall(search)
print found
如果您仍然需要python 2版本的代码,只需使用regex
模块,该模块可以与pip2 install regex
一起安装。用Import regex
导入它,然后用regex.
替换所有re.
语句(即regex.compile
和regex.findall
),就这样了。它应该可以工作。此代码适用于python 2.7
import re
with open('UTF32.red.codes','rb') as emof:
codes = [emo.decode('unicode-escape').strip() for emo in emof]
emojis = re.compile(u"(%s)" % "|".join(map(re.escape,codes)))
search = ur'string to check \U0001F601'
found = emojis.findall(search)
print found
文件中要检查的字符串在哪里?我想这不应该在字符串中。此外,命名变量string
可能会造成混淆,因此您可能希望避免这样做。这是要捕获\U0001F601
的字符串,然后执行string=u'\U0001F601'
。更好的方法是使用不同的变量名,如search
或类似的名称。你说得对。这个信息不见了。python 2.7是否遇到任何错误?我想如果我们想解决这个问题,我们需要更多的信息。为什么你认为这个错误与这个问题有关?