从句子字符串中删除所有表情符号

时间:2017-06-25 18:23:46

标签: python unicode emoji

工作环境Python版本:

Python 3.6.1

我已经在StackOverflow和互联网上的其他地方尝试了许多方法 - 但我似乎仍然无法实现这一点。

我可以有任何字符串......并且表情符号可能会或可能不会被空格包围,可能在"或者在标签等之后...反正这些情况给我带来了一些麻烦。

这就是我所拥有的:

import sys
sys.maxunicode

emoji_pattern = re.compile("["
                           u"\U0001F600-\U0001F64F"  
                           u"\U0001F300-\U0001F5FF"
                           u"\U0001F680-\U0001F6FF"
                           u"\U0001F1E0-\U0001F1FF"
                           "]+", flags=re.UNICODE)

text = "" #This could be any text with or without emojis
text = emoji_pattern.sub(r'', text)

然而,上面显示或打印时仍然在文本中有表情符号。

text是一个unicode字符串,即type(text)返回<type 'unicode'>

那我错过了什么?我似乎还有表情符号。我也更喜欢一种反映这些Unicode名称可以在将来扩展的方法,所以我宁愿只使用一种方法来保存所有常规字符。

将文本编码为'unicode_escape',提供以下内容:

b'[1/2] Can you see yourself as Prompto or Aranea?\\nGet higher quality images from our FB page \\n\\u2b07\\ufe0f\\u2026'

原始未格式化文本为:

[1/2] Can you see yourself as Prompto or Aranea?
Get higher quality images from our FB page
⬇️…

1 个答案:

答案 0 :(得分:1)

不确定您认为sys.maxunicode的作用,但您的代码适用于Python 3.6。你确定你已经涵盖了所有的表情符号范围吗?

import re

emoji_pattern = re.compile("["
                           u"\U0001F600-\U0001F64F"  
                           u"\U0001F300-\U0001F5FF"
                           u"\U0001F680-\U0001F6FF"
                           u"\U0001F1E0-\U0001F1FF"
                           "]+", flags=re.UNICODE)

text = 'Actual text with emoji: ->\U0001F620\U0001F310\U0001F690\U0001F1F0<-'
print(text)
text = emoji_pattern.sub(r'', text)
print(text)

输出:

Actual text with emoji: -><-
Actual text with emoji: -><-

请注意,flags=re.UNICODE是Python 3.6中的默认值,因此不需要它。 Unicode字符串也是默认值,因此u"xxxx"可以只是"xxxx"