【问题标题】:Get all the children from xml tag using ElementTree使用 ElementTree 从 xml 标记中获取所有子项
【发布时间】:2018-05-06 10:43:09
【问题描述】:

我正在尝试使用 ElementTree 解析 XML 文件,并且在某些时候我只得到第一个孩子而不是标签内的所有孩子-以下是我的 XML 结构:-

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <sentences>
        <sentence id="2339">
            <text>I charge it at night and skip taking the cord with me because of the good battery life.</text>
            <aspectTerms>
                <aspectTerm term="cord" polarity="neutral" from="41" to="45"/>
                <aspectTerm term="battery life" polarity="positive" from="74" to="86"/>
            </aspectTerms>
        </sentence>
        <sentence id="812">
            <text>I bought a HP Pavilion DV4-1222nr laptop and have had so many problems with the computer.</text>
        </sentence>
        <sentence id="1316">
            <text>The tech guy then said the service center does not do 1-to-1 exchange and I have to direct my concern to the "sales" team, which is the retail shop which I bought my netbook from.</text>
            <aspectTerms>
                <aspectTerm term="service center" polarity="negative" from="27" to="41"/>
                <aspectTerm term="&quot;sales&quot; team" polarity="negative" from="109" to="121"/>
                <aspectTerm term="tech guy" polarity="neutral" from="4" to="12"/>
            </aspectTerms>
        </sentence>
    </sentences>

我想在每个“aspectTerm”标签中获取“term”。以下是我的代码:-

    import xml.etree.ElementTree as ET
    tree = ET.parse('Laptops_Train.xml')
    root = tree.getroot()
    df = pd.DataFrame()

    def getAspect(sentences):
        reviewList = []
        text = sentence.find('text').text
        reviewList.append(text)
        for aspectTerms in sentence.iter('aspectTerms'):
            #for aspectTerm in aspectTerms.iter('aspectTerm'): 
            aspect = aspectTerms.find('aspectTerm').get('term')
            print(aspect)
            return aspect

    aspectList = []
    for sentences in root.iter('sentences'):
        for sentence in sentences.iter('sentence'):
            aspectList.append(getAspect(sentence))

实际结果:

cord
class 'NoneType'
service center

预期结果:

[cord, battery life]
[]
[service center,&quot;sales&quot; team, tech guy]

提前致谢

【问题讨论】:

    标签: xml python-3.x elementtree


    【解决方案1】:

    使用具有 xpath 的 lxml 库更容易做到这一点。

    >>> from lxml import etree
    >>> tree = etree.parse('Laptops_Train.xml')
    >>> for aspectTerms in tree.xpath('.//aspectTerms'):
    ...     aspectTerms.xpath('aspectTerm/@term')
    ... 
    ['cord', 'battery life']
    ['service center', '"sales" team', 'tech guy']
    

    还要注意所有aspectTerms 都有一个Term 属性;没有空的会产生None

    编辑,灵感来自评论。

    >>> from lxml import etree
    >>> tree = etree.parse('Laptops_Train.xml')
    >>> for sentence in tree.xpath('.//sentence'):
    ...     sentence.xpath('.//aspectTerm/@term')
    ... 
    ['cord', 'battery life']
    []
    ['service center', '"sales" team', 'tech guy']
    

    【讨论】:

    • 非常感谢您的回答。您的解决方案要容易得多,但是当没有 aspectTerm 标签时,我必须插入空字符串。但毫无疑问,你做这项工作的方式要容易得多,但它不符合我的要求
    【解决方案2】:

    所以解决方案是使用 '.findall' 而不是 .find。因为 '.findall' 选择了所有的孩子。我的解决方案如下:-

        def getAspect(sentences):
            aspectList = []
            reviewList = []
            text = sentence.find('text').text
            reviewList.append(text)
            for aspectTerms in sentence.iter('aspectTerms'):
                #for aspectTerm in aspectTerms.iter('aspectTerm'): 
                aspect = aspectTerms.findall('aspectTerm')#.get('term')
                for aspectElem in aspect:
                    aspects = aspectElem.get('term')
                    aspectList.append(aspects)
                    print(aspects)
            return aspectList
    
    
        aspectList = []
        for sentences in root.iter('sentences'):
            for sentence in sentences.iter('sentence'):
                aspectList.append(getAspect(sentence))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-10
      • 2018-10-30
      • 2023-02-09
      • 2014-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多