2017-10-11 8 views
0

저는 프로그래밍에 익숙하지 않고 큰 텍스트 파일 (12000 줄 이상)을 정리하고 다른 .txt 파일에 쓰도록이 스크립트를 실행하고 있습니다. 문제는 파일을 작게 (대략 500 줄 정도) 실행하면 빠르게 실행되므로 결과적으로 파일 크기 때문에 시간이 걸리는 것입니다. 따라서 누군가이 코드를 효율적으로 만들 수 있도록 안내해 주시면 매우 감사하겠습니다.파일 프로세스에 쓰기가 더 효율적입니다.

input_file = open('bNEG.txt', 'rt', encoding='utf-8') 
    l_p = LanguageProcessing() 
    sentences=[] 
    for lines in input_file.readlines(): 
     tokeniz = l_p.tokeniz(lines) 
     cleaned_url = l_p.clean_URL(tokeniz) 
     remove_words = l_p.remove_non_englishwords(cleaned_url) 
     stopwords_removed = l_p.remove_stopwords(remove_words) 
     cleaned_sentence=' '.join(str(s) for s in stopwords_removed)+"\n" 
     output_file = open('cNEG.txt', 'w', encoding='utf-8') 
     sentences.append(cleaned_sentence) 
     output_file.writelines(sentences) 
    input_file.close() 
    output_file.close() 

편집 : 아래 답변으로 토론하도록하려면

input_file = open('chromehistory_log.txt', 'rt', encoding='utf-8') 
    output_file = open('dNEG.txt', 'w', encoding='utf-8') 
    l_p = LanguageProcessing() 
    #sentences=[] 
    for lines in input_file.readlines(): 
     #print(lines) 
     tokeniz = l_p.tokeniz(lines) 
     cleaned_url = l_p.clean_URL(tokeniz) 
     remove_words = l_p.remove_non_englishwords(cleaned_url) 
     stopwords_removed = l_p.remove_stopwords(remove_words) 
     #print(stopwords_removed) 
     if stopwords_removed==[]: 
      continue 
     else: 
      cleaned_sentence=' '.join(str(s) for s in stopwords_removed)+"\n" 

     #sentences.append(cleaned_sentence) 
     output_file.writelines(cleaned_sentence) 
    input_file.close() 
    output_file.close() 
+0

모든 행에 대해 output_file을 엽니 다. 루프 위로 "output_file = open ('cNEG.txt', 'w', encoding = 'utf-8')"을 시도해보십시오. –

+0

솔루션으로 회신 해 주셔서 감사합니다. @RalphErdt 그러나 취한 시간에는 큰 변화가 없었습니다. –

+0

아 .. 뭔가를 감독했습니다. "문장"으로 모든 문자열을 수집하고 모든 루프를 반복적으로 작성합니다. -> a) 그냥 루프에 cleaned_sentence를 써 넣으십시오 (그리고 "문장"에서 수집하지 마십시오). b) 모든 것을 모으고 루프 뒤에 "문장"을 씁니다. 나는 그 메모리가 적기 때문에 메모리 사용량은 적지 만 느린 메모리를 선호하기 때문에). –

답변

0

내 요구 사항에 맞게 몇 가지 다른 변경과 대답에 언급 한 바와 같이 수정 된 코드입니다 :

두 문제는이 여기 :

출력 파일을 열고 생성하고 루프에 데이터를 쓰십시오 - 입력 파일의 모든 행에 대해 이자형. 추가로 배열의 모든 데이터를 수집합니다 (문장).

A) 루프 전에 파일을 만들고 루프에 그냥 "cleaned_sentence"를 쓰기 (및 수집 "문장") 삭제 :

당신은 두 가지 가능성이있다.

b) "문장"의 모든 것을 수집하고 루프 이후에 "문장"을 한 번에 작성하십시오.

a)의 단점은 b)보다 약간 느리다는 것입니다 (OS가 b의 메모리를 스왑하지 않아도 됨). 하지만 이점은 다음과 같습니다. 이것은 파일이 얼마나 크고 컴퓨터의 메모리가 얼마나 적게 설치 되더라도 메모리를 덜 소비하며 작동합니다.

+0

추천대로 나는 두 가지 방법을 시도했지만 방법 (a)을 고수했습니다. 아직도 오랜 시간이 걸립니다. –

+0

수정 된 코드를 게시하십시오. 다른 파일의 시간과 행 수를 추가하십시오. –

+0

위에 편집 된 코드를 추가했습니다. –