首页 > 解决方案 > 如何删除字符串的类似 html 的部分?

问题描述

我有一个看起来像这样的字符串:

<b><!--
</b>if (window!= top)
top.location.href=location.href
<b>// -->
</b>
15 Minutes
EMIL (V.O.)
Just do what I do.  Say the same thing I
say.  Don't open your mouth.

我只想要从“15 分钟”开始的字符串,并且基于对 SO 上另一个问题的回答,我尝试使用这样的正则表达式:

def cleanhtml(raw_text):
    cleanr = re.compile('<.*?>.*?')
    cleantext = re.sub(cleanr, '', raw_text)
    return cleantext

但这不会清理"if (window!= top) top.location.href=location.href"字符串的一部分。那我应该为正则表达式使用什么?

PS:我没有一个 HTML 文件开始。原始数据文件已经.txt形成。

标签: pythonregexstring

解决方案


您可以使用已经构建的库来执行此操作。

html要转换您可以使用的文本部分html2text

import html2text

html = '''
<b><!--

</b>if (window!= top)

top.location.href=location.href

<b>// -->

</b>

15 Minutes

EMIL (V.O.)

Just do what I do.  Say the same thing I

say.  Don't open your mouth.
'''

text_maker = html2text.HTML2Text() 
text_maker.strong_mark = False ##This prevents **** being added for <b>
text_maker.handle(html)

#"15 Minutes EMIL (V.O.) Just do what I do. Say the same thing I say. Don't open\nyour mouth.\n\n"

如果您需要指定具体的divs,或者classes您将需要使用类似的东西BeautifulSoup


推荐阅读