【问题标题】:python parsing xml to fetch string greater than given valuepython解析xml以获取大于给定值的字符串
【发布时间】:2018-10-04 14:41:12
【问题描述】:

如何使用 python 解析 xml 文件,如果退出,我试图让“分数”大于 50。在我的 xml 文件中,它确实存在,它应该打印出 65,93。

Test.xml

    <analysis xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <description/>
    <alert url="/alert/224.xml" message="Hello"/>
    <warning url="/warning/2.xml">
    <score>65</score>
    </warning>
    <warning url="/warning/23.xml">
    <score>33</score>
    </warning>
    <warning url="/warning/233.xml">
    <score>93</score>
    </warning>
    <warning url="/warning/233.xml">
    <score>93</score>
    </warning>
    </analysis>

【问题讨论】:

    标签: python xml string parsing


    【解决方案1】:

    您可以使用BeautifulSoup 来解析xml 文件。然后对于每个分数,我们可以将该分数添加到set,这意味着没有重复(即我们不会输出93 两次)。

    import bs4
    soup = bs4.BeautifulSoup(open('Test.xml'))
    nums = set()
    for score in soup.findAll('score'):
        num = int(score.text)
        if num > 50:
            nums.add(num)
    
    print(' '.join(str(n) for n in nums))
    

    给出:

    65 93
    

    【讨论】:

    • 非常感谢乔,我认为以下行需要更新,(open('Test.xml'),"html.parser")..
    • @Mihir 取决于您需要什么解析器,但是是的,所有 python 安装都有标准的“html.parser”。
    【解决方案2】:

    使用 BeautifulSoup

    from bs4 import BeautifulSoup
    score_set=set()
    soup = BeautifulSoup(open('Test.xml'),"html.parser")
    for score in soup.findAll('score'):
        if (int(score.next_element)>50):
            score_set.add(int(score.next_element))
    print(score_set) # {65, 93}
    

    【讨论】:

    • 非常感谢 mad_ 引入“BeautifulSoup”导入。
    【解决方案3】:
    import xml.etree.ElementTree as ET
    
    tree = ET.parse("Test.xml")
    
    warnings = tree.findall("warning")
    
    values = map(lambda x: x.getchildren()[0].text, warnings)
    
    print ','.join(set(filter(lambda f: int(f)> 50, values)))
    

    【讨论】:

    • 不用担心,您无需循环多次,只需一次迭代即可完成所有操作,但我尝试将其拆分以显示各个阶段
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多