用Python打印XML文本文件?

2024-06-16 11:24:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我想打印两个标记之间的任何文本<en>,只要x='PERS',我在下面尝试过,但是输出不是我想要的。你知道吗

XML示例

<Text>
<PHRASE>
<en x='PERS'> John </en>
<V> Went </V>
<prep> to </prep>
<V> meet </V>
<en x='PERS'> Alex </en>
</PHRASE>
<PHRASE>
<en x='PERS'> Mark </en>
<V> lives </V>
<prep> in </prep>
<en x='LOC'> Florida </en>
</PHRASE>
<PHRASE>
<en x='PERS'> Nick </en>
<V> visited</V>
<en x='PERS'> Anna </en>
</PHRASE>
</TEXT>

我想要输出:约翰·亚历克斯,尼克·安娜。 但我得到了:马克。也就是说,我只想打印2人时,他们出现在一个短语

这是我写的代码,我用元素树。你知道吗

import xml.etree.ElementTree as ET
tree = ET.parse('output.xml')
root = tree.getroot()
print("------------------------PERS-PERS-------------------------------")
PERS_PERScount=0
for phrase in root.findall('./PHRASE'):
    ens = {en.get('x'): en.text for en in phrase.findall('en')}
    if 'PERS' in ens and 'PERS' in ens:
        print("PERS is: {}, PERS is: {} /".format(ens["PERS"], ens["PERS"]))
        #print(ens["ORG"])
        #print(ens["PERS"])
        PERS_PERScount = PERS_PERScount + 1
print("Number of PERS-PERS relation", PERS_PERScount)

我不确定问题是在打印或如果条件,或两者?!你知道吗


Tags: intreeforrootxmletenprint
2条回答

只有当属性为xen元素的数目等于"PERS"时,才可以添加一个简单的if检查来递增和打印:

for phrase in root.findall('./PHRASE'):
    # get all inner text of elements where `x` attribute equals `"PERS"`
    names = [p.text.strip() for p in phrase.findall('./en[@x="PERS"]')]

    # if therea are 2 of them, increment counter and print
    if len(names) == 2:
        PERS_PERScount += 1
        print('-'.join(names))

print("Number of PERS-PERS relation: ", PERS_PERScount)

^{}

输出:

John-Alex
Nick-Anna
Number of PERS-PERS relation:  2

这是:

#!/usr/bin/env python3

import xml.etree.ElementTree as ET

tree = ET.parse('output.xml')

root = tree.getroot()

print("            PERS-PERS               -")

for phrase in root:
    if phrase.tag == 'PHRASE':
        collected_names = []
        for elt in phrase:
            if elt.tag == 'en':
                if 'x' in elt.attrib and elt.attrib['x'] == 'PERS':
                    collected_names += [elt.text]
        if len(collected_names) >= 2:
            print(collected_names[0] + " - " + collected_names[1])

将输出:

$ ./test_script
            PERS-PERS               -
 John  -  Alex 
 Nick  -  Anna 

但我不确定这正是你想要的。你知道吗

相关问题 更多 >