2016-11-03 9 views
1

テキストファイルからストップワードを削除しようとしています。テキストファイルは9000個以上の文から構成され、それぞれが独自の行にあります。Python:txtファイル出力のストップワードが1行ではない

コードがほぼ正常に動作しているように見えますが、出力ファイルがテキスト文書から行構造を削除してしまったことは明らかです。

ここにコードがあります。

from nltk.corpus import stopwords 
from nltk.tokenize import word_tokenize 

with open(r"C:\\pytest\twitter_problems.txt",'r', encoding="utf8") as inFile, open(r"C:\\pytest\twitter_problems_filtered.txt",'w', encoding="utf8") as outFile: 
    stop_words = set(stopwords.words('english')) 
    words = word_tokenize(inFile.read()) 
    for w in words: 
     if w not in stop_words: 
      outFile.write(w) 
outFile.close() 

wordトークンの代わりに使用する必要があるライントークナイザがありますか?私はnltkの文書をチェックしましたが、実際にはそれを理解できません(私はまだこのようなものでは全く新しい初心者です)。あなたがライン構造を保持したい場合は

答えて

1

。このような何かうまくいくかもしれない:

with open(r"C:\\pytest\twitter_problems.txt",'r', encoding="utf8") as inFile, open(r"C:\\pytest\twitter_problems_filtered.txt",'w', encoding="utf8") as outFile: 
    stop_words = set(stopwords.words('english')) 
    for line in inFile.readlines(): 
     words = word_tokenize(line) 
     filtered_words = " ".join(w for w in words if w not in stop_words) 
     outFile.write(filtered_words + '\n') 

意図したとおりに動作します-statement withはあなたがよく目撃

+0

後てoutFileを閉じるために持っていない場合 - OPがなかった、単語間行方不明にスペースを追加します言及。 – alexis

+0

これは素晴らしい解決策でした!どうもありがとう! – cwinhall

2

、単に行毎にファイルを読み込み、各1の後に改行を追加します。私は、行毎にファイルを読み込むことをお勧め

with open(r"C:\\pytest\twitter_problems.txt",'r', encoding="utf8") as inFile, open(r"C:\\pytest\twitter_problems_filtered.txt",'w', encoding="utf8") as outFile: 
    stop_words = set(stopwords.words('english')) 
    for line in infile: 
     words = word_tokenize(line) 
     for w in words: 
      if w not in stop_words: 
       outFile.write(w) 
     output.write('\n') 
関連する問題