如何从推文中删除特殊字符(例如“ŒðŸ”)

How to delete special characters (such as `‘ŒðŸ’`) from tweets

我必须清除推文中的特殊字符,例如 👉👌💦✨。为了做到这一点,我遵循了这个策略(我使用 Python 3):

  1. 将推文从字节转换为字符串,将特殊字符转换为十六进制,因此 Ã 变为 \xc3\;
  2. 使用正则表达式,删除 b'b"(在字符串的开头)和 '"(在字符串的结尾) ) 在转换过程后由 Python 添加;
  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 数据中的特殊字符。任何帮助将不胜感激。

如果您只查找 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(),并为其指定您要保留的文本范围(可能包括表情符号)。