2016-03-04 171 views
0

我想打印一對標籤<en>之間的任何文本,只要x ='PERS',我在下面試過,但輸出結果不是我想要的。在Python中打印XML文本文件?

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> 

我想要的輸出:約翰 - 亞歷克斯,尼克 - 安娜。 但我得到了:Mark-Mark。這意味着我只打印2個PERS,當他們出現在一個短語中時

這是我寫的代碼,我使用了元素樹。

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) 

我不知道問題出在打印或if條件,或兩者兼而有之?!

+0

您的第一個「文本」標記與最後一個(寫入'TEXT')不匹配。你應該讓它們都相同,以免在解析時出現錯誤。 – zezollo

回答

1

可以添加一個簡單的if檢查來增加和打印,只有當en元件的與屬性x數目等於"PERS"是2(一對):

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) 

eval.in demo

輸出:

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

此:

#!/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 

,但我不知道這正是你想要的方式。