python正则表达式用<ul>和<li>替换<ul ...>和<li ...>标签,resp </li> </ul> </li ...> </ul ...>

时间:2014-03-13 06:24:09

标签: python regex html-lists

您好我想使用python regex从<ul><li>标签中删除所有属性。以下是我的源字符串:

peanut butter1
<ul id="ul0002" list-style="none">peanut butter2
    <li id="ul0002-0001" num="0000">2.0 to 6.0 mg of 17&#x3b2;-estradiol and</li>
    <li id="ul0002-0002" num="0000">0.020 mg of ethinylestradiol;</li>
    <li id="ul0002-0003" num="0000">0.25 to 0.30 mg of drospirenone and</li>
    <li id="ul0002-0004" num="0000">0.1 to 0.2 mg of cyproterone acetate,</li>peanut butter3
</ul>

我想输出的内容:

peanut butter1
<ul>peanut butter2
    <li>2.0 to 6.0 mg of 17&#x3b2;-estradiol and</li>
    <li>0.020 mg of ethinylestradiol;</li>
    <li>0.25 to 0.30 mg of drospirenone and</li>
    <li>0.1 to 0.2 mg of cyproterone acetate,</li>peanut butter3
</ul>

2 个答案:

答案 0 :(得分:2)

import re
for line in open('sample.html'):
    print re.sub('<(ul|li)[^>]*>', r'<\1>', line, flags=re.I),

以上将删除所有ul和li标签中的属性,无论一行上是否有一个或多个标签。此外,由于使用了re.I,因此搜索不区分大小写,并且会找到<UL...等标记并删除其属性。标签外的文字保持不变。

使用您的(修订的)示例html,上面的代码生成:

peanut butter1
<ul>peanut butter2
    <li>2.0 to 6.0 mg of 17&#x3b2;-estradiol and</li>
    <li>0.020 mg of ethinylestradiol;</li>
    <li>0.25 to 0.30 mg of drospirenone and</li>
    <li>0.1 to 0.2 mg of cyproterone acetate,</li>peanut butter3
</ul>

立即处理整个文件

如果数据不是太长,可以一次处理所有数据,而不是一次处理一行:

import re
string = open('sample.html').read()
string = re.sub('<(ul|li)[^>]*>', r'<\1>', string, flags=re.I)
print string

答案 1 :(得分:1)

试试这个:

    >>> xs='<li id="ul0002-0001" num="0000">2.0 to 6.0 mg of 17&#x3b2;-estradiol and</li>'
    >>> p=r'(<li|<ul|</ul)[^>]*(>)(.*)'
    >>> match=re.search(p,xs)
    >>> ''.join([match.group(1),match.group(2),match.group(3)])
        '<li>2.0 to 6.0 mg of 17&#x3b2;-estradiol and</li>'
    >>> xs='<ul id="ul0002" list-style="none">'
    >>> match=re.search(p,xs)
    >>> ''.join([match.group(1),match.group(2),match.group(3)])
        '<ul>'
相关问题