@15698-sai (開基 斎藤)

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

killedと表示されてしまう.

Q&A

Closed

解決したいこと

プログラムを実行した所killedと表示されてしまうのですが解決策を教えて頂きたいです.
ソースコードは5GBのxmlファイルを読み取り,soop-containsで1万行辺りのテキストファイルの数値がarticle-id_pmidだったら特定の文字列を含んだparagraphのテキストを抽出するというプログラムです.

該当するソースコード

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:-soup-contains("COVID-19") 
text = [t.text for t in texts]

#print('\n'.join(text))
xml.close()

#実行結果を指定のファイルに保存
with open ('re.txt','w')as txt:
  print(text,file=txt)
txt.close
0 likes

1Answer

メモリ不足でしょう。試しに以下のような 10MB の XML ファイルを作って soup = BeautifulSoup(xml, 'xml') で読み込んだところ、 Python のメモリ消費量は 1GB 弱になりました。 XML の構造にもよるでしょうが、ファイルサイズの100倍程度のメモリが必要そうです。

<items>
  <item>aaa</item>
  <item>aaa</item>
  (10MB分繰り返し)
</items>

BeautifulSoup ではなく xml.saxxml.dom.pulldom といったイベント駆動型 XML パーサを使えば、ファイルを一気に読み込む必要がないため、メモリ消費を現実的なレベルに抑えられると思います。ただし soup.select のようなセレクタは使えないので、テキストの抽出方法は再考する必要があります。

2Like

Your answer might help someone💌