Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python中构建规则的表情符号词汇表?_Python_Regex_Python 2.7_Python Unicode - Fatal编程技术网

如何在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是否遇到任何错误?我想如果我们想解决这个问题,我们需要更多的信息。为什么你认为这个错误与这个问题有关?