python - 使用 python 删除 @mentions、url 和 # 符号

标签 python regex python-3.x

尝试使用 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/

相关文章:

java - 匹配器在寻找匹配字符时如何遍历字符串?

regex - 如何生成开头或结尾不包含特定字符串的正则表达式?

java - 只有当它不匹配另一个模式时,如何替换所有匹配的模式?

python - 在执行过程中从 64 位 python.exe 切换到 32 位

python - 仅当问题存在时才显示问题评论

python - 将 ip 地址绑定(bind)到 urllib2 对我不起作用

python - lark : How to make literals appear in the tree

python-3.x - 类型错误 : metaclass conflict python 3; django 2

python - 在 AWS S3 中分块创建大型 zip 文件

python - 使用另一个数组搜索一个数组