编程语言
首页 > 编程语言> > 如何在python中构建常规词汇表?

如何在python中构建常规词汇表?

作者:互联网

我在纯文本UTF32.red.codes文件中有一个表情符号代码列表.文件的简单内容是

\U0001F600
\U0001F601
\U0001F602
\U0001F603 
\U0001F604
\U0001F605
\U0001F606
\U0001F609
\U0001F60A
\U0001F60B

基于question,我的想法是从文件的内容创建正则表达式以捕获表情符号.这是我最小的工作示例

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

发现总是空的.哪里错了?我正在使用python 2.7

解决方法:

您的代码将在python 3中正常运行(只需修复打印发现的打印(找到)).但是,在python 2.7中它不起作用,因为它的re模块有一个已知的bug(见this threadthis issue).

如果你仍然需要python 2版本的代码,只需使用regex模块,它可以与pip2安装正则表达式一起安装.然后用import regex导入它,替换所有re.正则表达式的语句. (即regex.compile和regex.findall)就是这样.它应该工作.

标签:python,regex,python-2-7,python-unicode
来源: https://codeday.me/bug/20190706/1397117.html