2012-06-21 3 views
2

프로그래밍 처음 소개. 필자는 디렉토리에서 XML 파일을 읽고 요소의 텍스트를 복사하여 출력 디렉토리에 써 넣기 위해 BeautifulSoup를 사용하는 Python 코드 (stackoverflow의 도움을 받아)를 작성했습니다.Python : 여러 파일을 한 번에 쓸 수있는 스크립트 실행

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")) 

문제는 내가 10 만 개 XML 파일을 실행하려면이 필요하다 : 여기 내 코드입니다. 나는 지난 밤에 프로그램을 시작했고, 나의 견적에 달리는 데 15 시간이 걸렸습니다. 한 번에 하나씩 읽고 쓰는 대신 한 번에 100 또는 1000을 읽거나 쓸 수있는 방법이 있습니까?

+0

파일 작성이 가장 느린 단계인지 확인 했습니까? BeautifulSoup로 XML 파일을 파싱하지 않습니까? –

+0

구문 분석은 병목 현상이 아니라고 생각합니다. 각 XMl 파일의 평균 크기는 약 50KB이기 때문입니다. – Levar

답변

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() 
+0

python 초급자의 질문 폐지 -이 코드의 매개 변수를 수정해야합니까, 아니면 그대로 실행해도 괜찮습니까? – Levar

+0

예제 코드가 제대로 작동한다고 가정하면이 코드는 유용 할 것입니다. – Trevor

+0

제안 해 주셔서 감사합니다. 나는 다음 달에 그것을 시험해 볼 것이다. – Levar

0

많은 생각을 싫어할 때 스레드를 사용할 수 있습니다. 파이썬의 GIL은 입출력 작업에서 해제되므로 스레드 풀을 실행하고 작업을 소비 할 수 있습니다.

관련 문제