5GBのxmlファイルを読み取り,soup-containsで1万行辺りのテキストファイルの数値がarticle-id_pmidだったら特定の文字列を含んだparagraphのテキストを抽出するというプログラムがあります.
このプログラムではBeautiful Soupを用いてテキストを抽出しているのですが、それだとkilledと表示されてしまい、メモリ不足ではないかと思い、1.xmlのような形に分割処理をしたいでのすが、可能なのでしょうか.
ソースコード
from bs4 import BeautifulSoup
#xmlファイル読み込み
with open('1.xml','r',encoding='utf-8') as xml:
soup = BeautifulSoup(xml, 'xml')
# IDが書かれたテキストファイルを改行コードで区切る
with open('1.txt') as b:
nums =[n.strip() for n in b.readlines()]
b.close()
nums= ','.join(f'"{n}"' for n in nums)
texts = soup.select(f'''
document:has(>passage >infon[key="article-id_pmid"]:-soup-contains({nums})) >
passage >
infon[key="type"]:-soup-contains("paragraph") ~ text:-soup-contains("first")
''')
text = [t.text for t in texts]
xml.close()
#実行結果を指定のファイルに保存
with open ('2.txt','w')as txt:
print(text,file=txt)
txt.close
1.xml
<collection>
<document>
<passage>
<infon key="article-id_pmid">1111</infon>
</passage>
<passage>
<infon key="type">paragraph</infon>
<text>which was first diagnosed in Wuhan. </text>
</passage>
</document>
<collection>
with open(...) as XXX:
しているxml
,b
,txt
をわざわざ.close()
していますが、それは不要では?Pythonで開いたファイルのクローズを忘れやすい人のためのwith文の使い方 そしてこの記事のように表示されたメッセージを略さずに提示してみてください。What does 'killed' mean when processing a huge CSV with Python, which suddenly stops? あと明示的にガベージコレクトしてみてはどうでしょう?【Python】メモリ開放でパフォーマンスを向上させる方法:-soup-contains()
は負荷の高い操作なので, それ無しで行ってみるとなにか違うかもparse_only
オプションで処理対象の XML entity を限定するなどの対応が考えられます。