使用 Python 从字符串中删除表情符号
- 2025-01-22 08:45:00
- admin 原创
- 63
问题描述:
我在 Python 中找到了这段用于删除表情符号的代码,但它不起作用。你能帮忙提供其他代码或修复这个问题吗?
我观察到我的所有表情符号都以 开头,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', 'xf0x9fx98x82', 'https://t.co/5N86jYipOI']
更新:我使用了其他代码:
emoji_pattern=re.compile(ur" " " [U0001F600-U0001F64F] # emoticons \n |\n [U0001F300-U0001F5FF] # symbols & pictographs\n |\n [U0001F680-U0001F6FF] # transport & map symbols\n |\n [U0001F1E0-U0001F1FF] # flags (iOS)\n " " ", re.VERBOSE)
emoji_pattern.sub('', word)
但这仍然没有删除表情符号并显示它们!有知道为什么吗?
解决方案 1:
在 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
输出
相关推荐
热门文章
项目管理软件有哪些?
热门标签
云禅道AD