如何从tweets中删除特殊字符(如“ŒðŸ”`)

2024-09-28 03:17:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须清除tweets中的特殊字符,如👉👌💦✨。为此,我遵循以下策略(我使用Python 3):

  1. 将tweet从字节转换为字符串以获得十六进制的特殊字符,因此Ã变成{}
  2. 使用正则表达式,删除转换过程后Python添加的b'b"(在字符串开头)和'或{}(在字符串末尾)
  3. 最后删除十六进制表示,同样使用正则表达式。在

这是我的代码:

import re
tweet = 'b"[/Very seldom~ will someone enter your life] to question\xc3\xa2\xe2\x82\xac\xc2\xa6 "'

#encoding to 'utf8'
tweet_en = tweet.encode('utf8')
#converting to string
tweet_str = str(tweet_en)
#eliminating the b' and b" at the begining of the string:
tweet_nob = re.sub(r'^(b\'b\")', '', tweet_str)
#deleting the single or double quotation marks at the end of the string:
tweet_noendquot = re.sub(r'\'\"$', '', tweet_nob)
#deleting hex
tweet_regex = re.sub(r'\\x[a-f0-9]{2,}', '', tweet_noendquot)
print('this is tweet_regex: ', tweet_regex)

最后的输出是:[/Very seldom~ will someone enter your life] to question "(我仍然不能从中删除最后的")。我想知道是否有更好更直接的方法来清除Twitter数据中的特殊字符。任何帮助都将不胜感激。在


Tags: theto字符串reyourstringwillregex
1条回答
网友
1楼 · 发布于 2024-09-28 03:17:56

如果您只需要查找ASCII字符,我认为这会很好地工作:

initial_str = 'Some text 👉👌💦✨ and some more text'
clean_str = ''.join([c for c in initial_str if ord(c) < 128])
print(clean_str)  # Some text  and some more text

您可以执行ord(c) in range(),并给它一个要保留的文本范围(可能包括表情符号)。在

相关问题 更多 >

    热门问题