Skip to main content
 首页 » 编程设计

python之从字符串中删除具有特定约束的单词

2024年10月25日24haluo1

我在 python 中使用 RE 删除文本中的所有符号和一些以 #、@ 等开头的单词,但无法删除以 http 开头的单词。我该怎么做? 这是我的代码。

text = http://twitpic.com/2y1zl - Awww, that's a bummer.  You shoulda got David Carr of Third :)))) 
line = re.sub('([!,".?$&\)\(\/\\,:;-]|@\w+|#\w+|http\w+)', '', text) 

我得到的输出是:

httptwitpiccom2y1zl  Awww that's a bummer  You shoulda got David Carr of Third 

我不想在我的输出中出现 httptwitpiccom2y1zl。有什么帮助吗?谢谢。

请您参考如下方法:

([!,".?$&\)\(\/\\,:;-]|@\w+|#\w+|http\S+) 

您可以简单地使用它。查看演示。

https://regex101.com/r/wU7sQ0/51

line = re.sub('([!,".?$&\)\(\/\\,:;-]|@\w+|#\w+|http\S+)', '', text)