私は次のxmlファイルを持っていますので、内容を<seg>
に読み込んで、Pythonでプレーンテキストファイルに保存します。私はDOMモジュールを使いました。xmlファイルの一部の内容を読み込んでテキストファイルに書き込む方法は?
<?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()
コード上に実行されているが、それは正常に画面上のすべての行を印刷するが、file.txtなどは、最後<seg>
(SEGのID = 4)のいずれかのラインを有し、実際にはすべての文章をファイルに保存します。私のコードに何か問題がありますか?
あなただけのファイルへの最後の見つかった項目を執筆しているためです。ファイルへの書き込みもループ内にある必要があります。 –
あなたが言っていたように、私はファイル書き込みコマンドをループに入れて何度も試しましたが、常に同じ最後の文でした。 – Victor
'a'を追加するにはファイルを開く必要があります。それ以外の場合はファイルを 'w'で上書きします。 –