繁体   English   中英

python解析xml以获取大于给定值的字符串

[英]python parsing xml to fetch string greater than given value

如何使用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>

您可以使用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

使用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}
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)))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM