我有一個相當大的 XML 檔案,如下所示:
<corpus>
<dialogue speaker="A">
<sentence tag1="a" tag2="b"> Hello </sentence>
</dialogue>
<dialogue speaker="B">
<sentence tag1="cc" tag2= "dd"> How are you </sentence>
<sentence tag1="ff" tag2= "e"> today </sentence>
</dialogue>
<dialogue speaker="A">
<sentence tag1="d" tag2= "bbb"> Great </sentence>
<sentence tag1="f" tag2= "dd"> How about you </sentence>
</dialogue>
<dialogue speaker="B">
<sentence tag1="a" tag2= "dd"> me too </sentence>
</dialogue>
</corpus>
我需要洗掉子元素標簽,因此碎片文本在父元素下再次變得完整,輸出如下所示:
<corpus>
<dialogue speaker="A">
Hello
</dialogue>
<dialogue speaker="B">
How are you today
</dialogue>
<dialogue speaker="A">
Great How about you
</dialogue>
<dialogue speaker="B">
me too
</dialogue>
</corpus>
我試過了element.strip(),element.tag.strip()但沒有輸出......這是我的代碼:
f = ET.parse("file.xml")
root = f.getroot()
for s in root.findall("sentence"):
text = s.tag.strip("sentence")
print(text)
我究竟做錯了什么?感謝大家的幫助!!
uj5u.com熱心網友回復:
您快到了。要獲得您的輸出,請嘗試:
for d in root.findall(".//dialogue"):
for s in d.findall('.//sentence'):
if s.text:
new_t = s.text.strip()
d.remove(s)
d.text=new_t
print(ET.tostring(root).decode())
那應該輸出你需要的東西。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/478393.html
