Ich habe eine folgende XML-Datei, ich möchte den Inhalt in <seg>
lesen und sie in einer einfachen Textdatei mit Python speichern. Und ich habe das DOM-Modul benutzt.Wie lese ich einige Inhalte von XML-Dateien und schreibe sie in eine Textdatei?
<?xml version="1.0"?>
<mteval>
<tstset setid="default" srclang="any" trglang="TRGLANG" sysid="SYSID">
<doc docid="ntpmt-dev-2000/even1k.cn.seg.txt">
<seg id="1">therefore , can be obtained having excellent properties (good stability and solubility of the balance of the crystal as a pharmaceutical compound is not possible to predict .</seg>
<seg id="3">compound (I) are preferably crystalline , in particular , has good stability and solubility equilibrium and suitable for industrial prepared type A crystal is preferred .</seg>
<seg id="4">method B included in the catalyst such as DMF , and the like in the presence of a compound of formula (II) with thionyl chloride or oxalyl chloride to give an acyl chloride , in the presence of a base of the acid chloride with alcohol (IV) (O) by reaction of esterification .</seg>
</doc>
</tstset>
</mteval>
from xml.dom.minidom import parse
import xml.dom.minidom
dom = xml.dom.minidom.parse(r"path_to_xml file")
file = dom.documentElement
seg = dom.getElementsByTagName("seg")
for item in seg:
sent = item.firstChild.data
print(sent,sep='')
file = open(r'file.txt','w')
file.write(sent)
file.close()
während oberhalb Codes ausgeführt wird, erfolgreich alle Linien auf dem Bildschirm gedruckt werden, aber die datei.txt hat nur eine Zeile der letzten <seg>
(SEG ID = 4), Eigentlich möchte ich alle Sätze in der Datei speichern. Stimmt etwas nicht mit meinen Codes?
Das ist, weil Sie nur die letzte gefundene Element in die Datei zu schreiben sind. Das Schreiben in die Datei muss auch innerhalb der Schleife erfolgen. –
Wie du schon sagtest, habe ich die Befehle zum Schreiben von Dateien in die Schleife geschrieben und mehrmals versucht, aber es war immer der gleiche, immer der letzte Satz. – Victor
Sie müssen die Datei zum Anhängen von 'a' öffnen, andernfalls wird die Datei mit 'w' überschrieben. –