2016-04-01 23 views
0

XML dosyam var ve element tree kullanıyorum. Onlar <NEG> etiketi yoksaPython-XML: Belirli bir etiketin bulunup bulunmadığını kontrol edip devam edilsin mi?

<TEXT> 

<PHRASE> 
<en x='LOC'>NY</en> 
<PREP>is</PREP> 
<PREP>not</PREP> 
<en x='LOC'>Mexico</en> 
</PHRASE> 

<PHRASE> 
<en x='LOC'>NY</en> 
<PREP>is</PREP> 
<PREP>in</PREP> 
<en x='LOC'>USA</en> 
</PHRASE> 

<PHRASE> 
<en x='ORG'>Alpha</en> 
<CONJ>is</CONJ> 
<NEG>not</NEG> 
<PREP>in</PREP> 
<en x='LOC'>Atlanta</en> 
</PHRASE> 

<PHRASE> 
<en x='ORG'>Google</en> 
<CONJ>is</CONJ> 
<PREP>in</PREP> 
<en x='LOC'>California</en> 
</PHRASE> 


</TEXT> 

Ben çiftleri ayıklamak istiyorum:

NY-ABD

: Ben çıkış olmak istiyorum

örneğin ben bu XML piton var

:

tarihinde Kaliforniya

Bu çalıştı

neg= elt.findall('NEG') 
       if neg is None: 
       continue 

ama sadece bunu yapabilirsiniz PHRASE başına bir NEG eleman varsa o

import xml.etree.ElementTree as ET 
tree = ET.parse('TrainBaseEnglish.xml') 
root = tree.getroot() 
print("------------------------ORG-LOC-------------------------------") 
ORG_LOCcount=0 
for phrase in root.findall('./PHRASE'): 
    ens = {en.get('x'): en.text for en in phrase.findall('en')} 
    if 'ORG' in ens and 'LOC' in ens: 
     print("ORG is: {}, LOC is: {} /".format(ens["ORG"], ens["LOC"])) 
     #print(ens["ORG"]) 
     #print(ens["PERS"]) 
     ORG_LOCcount = ORG_LOCcount + 1 
print("Number of ORG_LOC relation", ORG_LOCcount) 
print("------------------------LOC-LOC-------------------------------") 
LOC_LOCcount=0 
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'] == 'LOC': 
        collected_names += [elt.text] 
     if len(collected_names) >= 2: 
      print("LOC is: {}, LOC is: {} /".format(collected_names[0],collected_names[1])) 
      LOC_LOCcount = LOC_LOCcount + 1 
print("Number of LOC_LOC relation", LOC_LOCcount) 

cevap

0

işe yaramadı

import xml.etree.ElementTree as ET 

xml_string = '''<TEXT> 

<PHRASE> 
<en x='LOC'>NY</en> 
<PREP>is</PREP> 
<PREP>not</PREP> 
<en x='LOC'>Mexico</en> 
</PHRASE> 

<PHRASE> 
<en x='LOC'>NY</en> 
<PREP>is</PREP> 
<PREP>in</PREP> 
<en x='LOC'>USA</en> 
</PHRASE> 

<PHRASE> 
<en x='ORG'>Alpha</en> 
<CONJ>is</CONJ> 
<NEG>not</NEG> 
<PREP>in</PREP> 
<en x='LOC'>Atlanta</en> 
</PHRASE> 

<PHRASE> 
<en x='ORG'>Google</en> 
<CONJ>is</CONJ> 
<PREP>in</PREP> 
<en x='LOC'>California</en> 
</PHRASE> 


</TEXT> 
''' 

xml = ET.fromstring(xml_string) 
phrases = xml.findall("PHRASE") 

for phrase in phrases: 
    neg = phrase.find("NEG") 
    if neg is None: 
     continue 
    print neg 

Eğer PHRASE başına birden fazla NEG unsurları bekliyor ve gerek ise Bu nedenle .findall kullanın, .findall bir liste döndürdüğünden, neg uzunluğunu kontrol etmelisiniz.

for phrase in phrases: 
    neg = phrase.findall("NEG") 
    if len(neg) == 0: 
     continue 
    print neg 
İlgili konular