【问题标题】:How to build a regular vocabulary of emoticons in python?如何在python中建立一个常规的表情符号词汇表?
【发布时间】:2016-04-13 09:22:44
【问题描述】:

我在文件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

found 始终为空。我哪里错了?我正在使用 python 2.7

【问题讨论】:

  • 您的文件中的string to check 在哪里?我想这不应该在string 中。此外,命名变量 string 可能会造成混淆,因此您可能需要避免这样做。
  • 这是要捕获的字符串\U0001F601
  • 然后执行string = u'\U0001F601'。更好的是,使用不同的变量名称,例如 search 或类似名称。
  • 你说得对。缺少此信息。蟒蛇2.7
  • 您是否遇到任何错误?我认为如果我们想解决这个问题,我们需要更多信息。

标签: python regex python-2.7 python-unicode


【解决方案1】:

您的代码将在 python 3 中运行良好(只需将 print found 修复为 print(found))。但是,在 python 2.7 中它不起作用,因为它的 re 模块有一个已知的错误(参见 this threadthis issue)。

如果你还需要python 2版本的代码,就用regex模块,可以用pip2 install regex安装。用import regex 导入它,然后用regex. 替换所有re. 语句(即regex.compileregex.findall),就是这样。它应该可以工作。

【讨论】:

  • 你认为这个bug为什么和这个问题有关?
【解决方案2】:

此代码适用于 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-23
    • 1970-01-01
    • 2018-04-05
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多