【问题标题】:How to remove the html-like part of a string?如何删除字符串的类似 html 的部分?
【发布时间】:2021-03-03 00:47:19
【问题描述】:

我有一个如下所示的字符串:

<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" 部分。那我应该为正则表达式使用什么?

P.S.:我没有 HTML 文件。原始数据文件已经是.txt 形式。

【问题讨论】:

  • HTML 解析很难。使用第三方库,例如bleach。
  • 见stackoverflow.com/questions/11229831/…。那里的答案更详细。
  • 一般来说,用正则表达式解析 HTML 被认为是一个坏主意(甚至可能是不可能的)。另一个流行的第三方库名为Beautiful Soup。

标签: python regex string


【解决方案1】:

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

要转换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 之类的内容

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-10
    • 2019-11-17
    • 2013-08-10
    • 1970-01-01
    • 2022-11-28
    • 1970-01-01
    • 2017-07-02
    相关资源
    最近更新 更多