尝试使用 python 从 Twitter 数据中删除 @mentions、url 和 # 符号。 获取
lets take action! fitness health
来自
@BBCNews lets take action! #fitness #health https://www.url.com
代码:
import re
df1 = re.sub(r'(?:\@|https?\://|#)\S+', '', df)
但这会产生“让我们采取行动!”,我很难修复我的正则表达式,但我认为我已经接近了。如何修复我的正则表达式?
最佳答案
您的模式不正确,因为您还指定删除 #
字符后的 \S+
字符。相反,将您的模式更改为,
>>> re.sub(r'(@|https?)\S+|#', '', text)
' lets take action! fitness health '
正则表达式分解
(@ # match '@'
| # OR
https? # "http" or "https", followed by...
)
\S+ # one or more characters that aren't whitespace
| # OR
# # hashtag
作为奖励,第三方 tweet-processor模块提供了大部分开箱即用的功能,并具有可选的自定义功能。
import preprocessor as p
p.clean(text)
# 'lets take action!'
# customise what you want removed
p.set_options(p.OPT.MENTION, p.OPT.URL,)
p.clean(text)
# 'lets take action! #fitness #health'
p.clean(text).replace('#', '')
# 'lets take action! fitness health'
关于python - 使用 python 删除 @mentions、url 和 # 符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56659227/