【问题标题】:capture and remove beginning and end xml open and close tag with regex [duplicate]使用正则表达式捕获并删除开始和结束xml打开和关闭标记[重复]
【发布时间】:2021-03-04 09:30:48
【问题描述】:

我有以下 XML:

<data xmlns="">
<color>blue green</color>
<install>No</install>
<days>4</start>
</data>

我希望从漂亮的汤元素中删除 ''、'' 以及打开和关闭标签。

输出应该是:

Color: blue green, install: no, days: 4

这是我尝试过的:

new = re.sub(r'(/>)</data>.+', '</data>', new)

我刚学正则表达式,请见谅。

【问题讨论】:

标签: python-3.x regex beautifulsoup


【解决方案1】:

如果你想使用正则表达式来提取你的 XML,可以使用这个:

import re

txt = """
</data>\<data xmlns="">
<color>blue green</color>
<install>No</install>
<days>4</start>
</data>
"""
x = re.findall("(?<=<)([^\/>]+)>(.+)(?=<)", txt)

result=[]
for i in range(len(x)):
    result.append(x[i][0] +': ' + x[i][1] )
print(', '.join(result))

输出:

color: blue green, install: No, days: 4

https://regex101.com/r/Yqtnkx/1

性能不是很好,但希望对你有帮助。

【讨论】:

    【解决方案2】:

    根据 cmets,可以使用 BeautifulSoup 而不是正则表达式来实现结果。

    您需要做的就是找到标签数据。然后循环通过findChildren()。这将允许您捕获标签名称和文本。

    例如:

    from bs4 import BeautifulSoup
    
    html = '''<data xmlns="">
    <color>blue green</color>
    <install>No</install>
    <days>4</start>
    </data>'''
    
    soup=BeautifulSoup(html,'lxml') 
    data=soup.find('data')
    
    results = []
    for x in data.findChildren():
        results.append(f'{x.name}: {x.text.strip()}')
    
    separator = ', '
    print(separator.join(results))
    

    输出

    color: blue green, install: No, days: 4
    

    【讨论】:

    • 感谢@greg 的建议和解决方案!
    猜你喜欢
    • 2011-03-29
    • 2010-11-21
    • 1970-01-01
    • 2010-10-05
    • 1970-01-01
    • 2011-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多