从 Python 中的字符串中删除表情符号

新手上路,请多包涵

我在 Python 中找到了这段用于删除表情符号的代码,但它不起作用。你能帮忙处理其他代码或解决这个问题吗?

我观察到我所有的 emjois 都以 \xf 开头,但是当我尝试搜索 str.startswith("\xf") 时,出现无效字符错误。

 emoji_pattern = r'/[x{1F601}-x{1F64F}]/u'
re.sub(emoji_pattern, '', word)

这是错误:

 Traceback (most recent call last):
  File "test.py", line 52, in <module>
    re.sub(emoji_pattern,'',word)
  File "/usr/lib/python2.7/re.py", line 151, in sub
    return _compile(pattern, flags).sub(repl, string, count)
  File "/usr/lib/python2.7/re.py", line 244, in _compile
    raise error, v # invalid expression
sre_constants.error: bad character range

列表中的每一项都可以是一个单词 ['This', 'dog', '\xf0\x9f\x98\x82', 'https://t.co/5N86jYipOI']

更新:我使用了其他代码:

 emoji_pattern=re.compile(ur" " " [\U0001F600-\U0001F64F] # emoticons \
                                 |\
                                 [\U0001F300-\U0001F5FF] # symbols & pictographs\
                                 |\
                                 [\U0001F680-\U0001F6FF] # transport & map symbols\
                                 |\
                                 [\U0001F1E0-\U0001F1FF] # flags (iOS)\
                          " " ", re.VERBOSE)

emoji_pattern.sub('', word)

但这仍然不会删除表情符号并显示它们!任何线索为什么会这样? 在此处输入图像描述

原文由 Mona Jalal 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 646
2 个回答

我正在通过@jfs 更新我对此的回答,因为我之前的回答未能说明其他 Unicode 标准,如拉丁语、希腊语等。StackOverFlow 不允许我删除我之前的回答,因此我正在更新它以匹配最可接受的答案到这个问题。

 #!/usr/bin/env python
import re

text = u'This is a smiley face \U0001f602'
print(text) # with emoji

def deEmojify(text):
    regrex_pattern = re.compile(pattern = "["
        u"\U0001F600-\U0001F64F"  # emoticons
        u"\U0001F300-\U0001F5FF"  # symbols & pictographs
        u"\U0001F680-\U0001F6FF"  # transport & map symbols
        u"\U0001F1E0-\U0001F1FF"  # flags (iOS)
                           "]+", flags = re.UNICODE)
    return regrex_pattern.sub(r'',text)

print(deEmojify(text))

这是我之前的回答,不要用这个。

 def deEmojify(inputString):
    return inputString.encode('ascii', 'ignore').decode('ascii')

原文由 Abdul-Razak Adam 发布,翻译遵循 CC BY-SA 4.0 许可协议

在 Python 2 上,您必须使用 u'' 文字来创建 Unicode 字符串。此外,您应该传递 re.UNICODE 标志并将输入数据转换为 Unicode(例如 text = data.decode('utf-8') ):

 #!/usr/bin/env python
import re

text = u'This dog \U0001f602'
print(text) # with emoji

emoji_pattern = re.compile("["
        u"\U0001F600-\U0001F64F"  # emoticons
        u"\U0001F300-\U0001F5FF"  # symbols & pictographs
        u"\U0001F680-\U0001F6FF"  # transport & map symbols
        u"\U0001F1E0-\U0001F1FF"  # flags (iOS)
                           "]+", flags=re.UNICODE)
print(emoji_pattern.sub(r'', text)) # no emoji

输出

This dog 😂
This dog

注意: emoji_pattern 仅匹配部分表情符号(并非全部)。查看 哪些字符是表情符号

原文由 jfs 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏