2016-07-25 22 views
-1

私が収集したメッセージの列を持つ.csvファイルがあります。その列のすべての単語の単語頻度リストを取得したいと考えています。ここに私がこれまで持っているものがあります。私はどこで間違いを犯したのか分からず、助けていただければ幸いです。編集:予想される出力は、単語のリスト全体とその数(重複なし)を別の.csvファイルに書き出すことです。PythonのCSV列からの単語頻度

import csv 
from collections import Counter 
from collections import defaultdict 

output_file = 'comments_word_freqency.csv' 
input_stream = open('comments.csv') 
reader = csv.reader(input_stream, delimiter=',') 
reader.next() #skip header 
csvrow = [row[3] for row in reader] #Get the fourth column only 

with open(output_file, 'rb') as csvfile: 
    for row in reader: 
     freq_dict = defaultdict(int) # the "int" part 
            # means that the VALUES of the dictionary are integers. 
     for line in csvrow: 
      words = line.split(" ") 
      for word in words: 
       word = word.lower() # ignores case type 
       freq_dict[word] += 1 

     writer = csv.writer(open(output_file, "wb+")) # this is what lets you write the csv file. 
     for key, value in freq_dict.items(): 
         # this iterates through your dictionary and writes each pair as its own line. 
      writer.writerow([key, value]) 
+0

あなたの出力は次のようになりどういう?また、単語の頻度を得るために何かをしているようには見えません。あなたはforループと.count()を使ってみましたか? – SAMO

+0

エラーメッセージが表示されますか?期待される結果は何ですか? [MCVE](http://stackoverflow.com/help/mcve)をご覧ください。 –

+0

私は理想的には、2つの列を持つoutput.csvファイル(重複なし)とその単語が現れる回数の1つの列を持つことが理想的です。 – TechPadawan24

答えて

0

あなたがアップロードしたコードはどこにでもありますが、これはあなたが何を得ているのかと思います。これは単語のリストとそれが元のファイルに現れた回数を返します。

words= [] 
with open('comments_word_freqency.csv', 'rb') as csvfile: 
    reader = csv.reader(csvfile) 
    reader.next() 
    for row in reader: 
     csv_words = row[3].split(" ") 
     for i in csv_words: 
       words.append(i) 

words_counted = [] 
for i in words: 
    x = words.count(i) 
    words_counted.append((i,x)) 

#write this to csv file 
with open('output.csv', 'wb') as f: 
writer = csv.writer(f) 
writer.writerows(edgl) 

はその後、リスト内の重複を取り除くためにだけ(設定を呼び出す)それに

set(words_counted) 

あなたの出力は次のようになります。

'this', 2 
'is', 1 
'your', 3 
'output', 5 
+0

特定の列の検索を制限するにはどうすればよいですか?行[column_number]を実行しますか? – TechPadawan24

+0

ただ更新しました。あなたはちょうど行[3]を使用する場合、それはあなたに4番目の列を与えます – SAMO

+0

私はcsvをインポートしましたが、まだ私はまだ次のエラーが表示されます: トレースバック(最新の呼び出し最後): ファイル "count_word_occurrences.py" 、in [3] in reader: NameError:name 'row'が定義されていません – TechPadawan24

関連する問題