2

プログラミングは初めてです。ディレクトリ内のXMLファイルを読み取り、BeautifulSoupを使用して要素のテキストをコピーし、これを出力ディレクトリに書き込むPythonコードを(stackoverflowの助けを借りて)作成しました。これが私のコードです:

from bs4 import BeautifulSoup
import os, sys

source_folder='/Python27/source_xml'

for article in os.listdir(source_folder):
    soup=BeautifulSoup(open(source_folder+'/'+article))

    #I think this strips any tags that are nested in the sample_tag
    clean_text=soup.sample_tag.get_text("  ",strip=True)

    #This grabs an ID which I used as the output file name
    article_id=soup.article_id.get_text("  ",strip=True)

    with open(article_id,"wb") as f:
        f.write(clean_text.encode("UTF-8"))

問題は、100,000個のXMLファイルに対してこれを実行する必要があることです。私は昨夜プログラムを開始しました、そして私の見積もりでは実行するのに15時間かかりました。たとえば、一度に1つずつ読み取りおよび書き込みを行う代わりに、一度に100または1000を読み取り/書き込みする方法はありますか?

4

2 に答える 2

3

マルチプロセッシングモジュールはあなたの友達です。次のようなプロセスプールを使用して、すべてのCPUでコードを自動的にスケーリングできます。

from bs4 import BeautifulSoup
import os, sys
from multiprocessing import Pool


source_folder='/Python27/source_xml'

def extract_text(article):
    soup=BeautifulSoup(open(source_folder+'/'+article))

    #I think this strips any tags that are nested in the sample_tag
    clean_text=soup.sample_tag.get_text("  ",strip=True)

    #This grabs an ID which I used as the output file name
    article_id=soup.article_id.get_text("  ",strip=True)

    with open(article_id,"wb") as f:
            f.write(clean_text.encode("UTF-8"))

def main():
    pool = Pool()
    pool.map(extract_text, os.listdir(source_folder))

if __name__ == '__main__':
    main()
于 2012-06-21T17:31:56.100 に答える
0

私がその考えを嫌うのと同じように、あなたはスレッドを使うことができます。PythonのGILはI/O操作でリリースされるため、スレッドプールを実行してジョブを消費することができます。

于 2012-06-21T17:30:11.407 に答える