使用Python删除子字符串

95

我已经从论坛中提取了一些信息。现在我拥有的是原始字符串:

string = 'i think mabe 124 + <font color="black"><font face="Times New Roman">but I don\'t have a big experience it just how I see it in my eyes <font color="green"><font face="Arial">fun stuff'

我不喜欢的是子字符串"<font color="black"><font face="Times New Roman">""<font color="green"><font face="Arial">"。除此之外,我想保留字符串的其他部分。因此,结果应该像这样:

resultString = "i think mabe 124 + but I don't have a big experience it just how I see it in my eyes fun stuff"

我该怎么做呢?实际上,我使用了beautiful soup从论坛中提取了上述字符串。现在,我可能更喜欢使用正则表达式来删除这部分内容。

这个字符串目前无法工作,因为它里面同时包含了 "' - juliomalegria
@ThiefMaster 感谢您的支持。我该如何删除它?这确实是一件丢脸的事情。 - Wenhao.SHE
@julio.alegria 如果你想进行一些测试,请把双引号之间的内容视为字符串。非常感谢。 - Wenhao.SHE
2
我不明白,你用beautifulsoup提取文本,但为什么在完成前想停止使用它呢? - Jochen Ritzel
3个回答

185
import re
re.sub('<.*?>', '', string)
"i think mabe 124 + but I don't have a big experience it just how I see it in my eyes fun stuff"
re.sub函数接受一个正则表达式,并用第二个参数替换字符串中的所有匹配项。在这种情况下,我们正在搜索所有标签('<.*?>'),并用空字符串('')替换它们。
re中,?用于非贪婪搜索。
有关re模块的更多信息。

3
非常有帮助,谢谢。我在我的项目中使用这段代码来删除推特推文中的提及(@s)- re.sub('@.*? ','',tweetText)。 - sumanth232
我需要从“mens tommy hilfiger knot boatshoe midnight uk size 6.5”中删除“size 6.5”这样的模式。如果我使用“re.sub('size.*?[0-9]+', '', shoe)”,我会得到“mens tommy hilfiger knot boatshoe midnight uk .5”。 - keshav

18
>>> import re
>>> st = " i think mabe 124 + <font color=\"black\"><font face=\"Times New Roman\">but I don't have a big experience it just how I see it in my eyes <font color=\"green\"><font face=\"Arial\">fun stuff"
>>> re.sub("<.*?>","",st)
" i think mabe 124 + but I don't have a big experience it just how I see it in my eyes fun stuff"
>>> 

-6
BeautifulSoup(text, features="html.parser").text 

对于那些在我的回答中寻找深入信息的人,抱歉。

我来解释一下。

Beautifulsoup是一个广泛使用的Python包,它帮助用户(开发者)在Python中与HTML交互。

上面的代码只是将所有HTML文本(text)转换为Beautifulsoup对象 - 这意味着在幕后它会解析所有内容(给定文本中的每个HTML标记)。

完成后,我们只需从HTML对象中请求所有文本即可。


请不要仅发布代码作为答案,还要提供解释您的代码做了什么以及如何解决问题。带有解释的答案通常具有更高的质量,并且更有可能吸引赞同。 - Mark Rotteveel
1
抱歉,有时候我觉得问题非常直接,真正的答案就是实际的实现。 - Benny Elgazar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接