2017-10-11 11 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() 

EDIT:他のいくつかの変更を加えての回答で述べたように以下が答えとして議論を持っているために、私の要件

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を書き込むだけで( "sentences"に集まらない)b)すべてを収集し、ループの後に "sentences"を書くだけです。私はそれがより少ないメモリ集約が、より少し遅いために)好む。 –

答えて

0

に合うように修正されたコードです:

2つの問題されていますここでは:

出力ファイルを開いて作成し、ループ内のデータを書き込む - 入力ファイルのすべての行についてe。さらに、配列内のすべてのデータを収集します(文章)。

次の2つの可能性があります。

a)はループの前にファイルを作成し、ループの中でだけ「cleaned_sentence」を書き込み(および収集「文章」を削除します)。

b) "sentences"内のすべてを収集し、ループの後ですぐに "sentences"と書いてください。

a)の欠点は:b)(OSがbのためにメモリを交換する必要がない限り)b)より少し遅いことです。しかし利点は次のとおりです。これはメモリの消費量が少なく、ファイルの大きさとコンピュータのメモリ容量の少なさに関係なく機能します。

+0

あなたがお勧めしたように私は両方の方法を試しましたが、方法(a)に固執しました。それでも時間がかかります。 –

+0

訂正したコードを投稿してください。異なるファイルの時間と行数を追加します。 –

+0

編集したコードを上に追加しました –

関連する問題