如何消除html标记?

2024-09-27 00:14:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我从页面中得到第一段,并试图提取适合作为标签或关键字的单词。在某些段落中有链接,我想删除标记:

例如,如果文本是

A <b>hex triplet</b> is a six-digit, three-<a href="/wiki/Byte"
enter code heretitle="Byte">byte</a> ...

我想移除

^{pr2}$

以这个结束

^{3}$

这样的正则表达式不起作用:

>>> text = """A <b>hex triplet</b> is a six-digit, three-<a href="/wiki/Byte"
    enter code heretitle="Byte">byte</a> ..."""
>>> f = re.findall(r'<.+>', text)
>>> f
['<b>hex triplet</b>', '</a>']
>>>

最好的办法是什么?在

我发现了几个类似的问题,但我认为没有一个能解决这个问题。在

使用beauthoulsoup extract示例更新(extract删除包含其文本的标记,并且必须分别为每个标记运行:

>>> soup = BeautifulSoup(text)
>>> [s.extract() for s in soup('b')]
[<b>hex triplet</b>]
>>> soup
A  is a six-digit, three-<a href="/wiki/Byte" enter code heretitle="Byte">byte</a> ...
>>> [s.extract() for s in soup('a')]
[<a href="/wiki/Byte" enter code heretitle="Byte">byte</a>]
>>> soup
A  is a six-digit, three- ...
>>> 

更新

对于有相同问题的人:正如brendanlong所说,this answer使用HtmlParser效果最好。在


Tags: iswikicodeextractbytethreehrefenter
3条回答

+量词是贪婪的,这意味着它将找到最长的匹配。添加一个?以强制它找到最短的匹配项:

>>> re.findall(r'<.+?>', text)
['<b>', '</b>', '</a>']

编写regex的另一种方法是显式地排除标记内的右尖括号,使用[^>]而不是.。在

^{pr2}$

这种方法的一个优点是它还将匹配换行符(\n)。如果添加^{}标志,.也可以得到相同的行为。在

>>> re.findall(r'<.+?>', text, re.DOTALL)
['<b>', '</b>', '<a href="/wiki/Byte"\n    enter code heretitle="Byte">', '</a>']

要去掉标记,请使用re.sub

>>> re.sub(r'<.+?>', '', text, flags=re.DOTALL)
'A hex triplet is a six-digit, three-byte ...'

这只是剥离标签的基本元素。包括缺少的元素,
下面的\w表示带前缀和正文的限定unicode标记名,
它需要一个join()语句来形成子表达式。解析的优点
使用regex的html/xml不会在第一个格式错误的实例上失败,这
使它非常适合修理它!缺点是速度慢,尤其是
使用unicode。在

不幸的是,剥离标记会破坏内容,因为根据定义,标记 格式化内容。在

在一个大网页上试试这个。这应该可以翻译成python。在

$rx_expanded = '
<
(?:
    (?:
       (?:
           (?:script|style) \s*
         | (?:script|style) \s+ (?:".*?"|\'.*?\'|[^>]*?)+\s*
       )> .*? </(?:script|style)\s*
    )
  |
    (?:
        /?\w+\s*/?
      | \w+\s+ (?:".*?"|\'.*?\'|[^>]*?)+\s*/?
      | !(?:DOCTYPE.*?| .*? )
    )
)
>
';

$html =~ s/$rx_expanded/[was]/xsg;

Beautiful Soup就是你问题的答案!试试看,真是太棒了!在

一旦使用了Html解析,它就会变得非常简单。在

>>> text = """A <b>hex triplet</b> is a six-digit, three-<a href="/wiki/Byte"
... enter code heretitle="Byte">byte</a> ..."""
>>> soup = BeautifulSoup(text)
>>> ''.join(soup.findAll(text=True))
u'A hex triplet is a six-digit, three-byte ...'

如果要提取的所有文本都包含在一些外部标记中,例如<body> ... </body>或某些{},那么可以执行以下操作(本图假设您要提取的所有文本都包含在<body>标记中)。现在,您可以选择性地从一些所需的标记中提取文本。在

(查看文档和示例,您会发现许多解析DOM的方法)

^{pr2}$

相关问题 更多 >

    热门问题