2016-12-19 7 views
-1

私はそれに関連するすべての値のための1つのキーを持つ辞書をループするmain関数を作成しています。辞書をすべて小文字にすることができないので、私は問題を抱えています。私は.lowerを使用しようとしましたが、無駄です。また、プログラムは、文章の言葉を見て、ユーザが以前に「幸せ」、「悲しい」、または「中立」と呼んでいた文中の3つの辞書に基づいて、どのラベルを文に当てはめるかを推測します。Pythonで辞書をルーピング

出力例は次のようになります

Sentence: i started screaming incoherently about 15 mins ago, this is B's attempt to calm me down. 
    0 appear in happy 
    0 appear in neutral 
    0 appear in sad 
I think this is sad. 
You think this is: sad 
Okay! Updating. 

CODE:

import csv 

def read_csv(filename, col_list): 
"""This function expects the name of a CSV file and a list of strings 
representing a subset of the headers of the columns in the file, and 
returns a dictionary of the data in those columns, as described below.""" 

    with open(filename, 'r') as f: 
     # Better covert reader to a list (items represent every row) 
     reader = list(csv.DictReader(f)) 
     dict1 = {} 
     for col in col_list: 
      dict1[col] = [] 
      # Going in every row of the file 
      for row in reader: 
       # Append to the list the row item of this key 
       dict1[col].append(row[col]) 
    return dict1 

def main(): 
    dictx = read_csv('words.csv', ['happy']) 
    dicty = read_csv('words.csv', ['sad']) 
    dictz = read_csv('words.csv', ['neutral']) 
    dictxcounter = 0 
    dictycounter = 0 
    dictzcounter = 0 
    a=str(raw_input("Sentence: ")).split(' ') 
    for word in a : 
     for keys in dictx['happy']: 
      if word == keys: 
       dictxcounter = dictxcounter + 1 
     for values in dicty['sad']: 
      if word == values: 
       dictycounter = dictycounter + 1 
     for words in dictz['neutral']: 
      if word == words: 
       dictzcounter = dictzcounter + 1 
    print dictxcounter 
    print dictycounter 
    print dictzcounter 
+0

'col_list'が_one_文字列のリストである場合、この式はアンパックエラーのためにクラッシュする必要があります:' dict1 = dict((k、v.lower()for k、v in col_list) '。正しいコードを表示していますか?同じステートメントでも、ループで構築した辞書が上書きされます。これはおそらく、コードが期待どおりに機能しない理由を説明するものです。 – DyZ

+0

'read_csv'に渡すものは、' ['happy'] 'という文字列のリストです。そしてこのリストは仮引数 'col_list'の値になります。 – DyZ

+0

私は>>>で何を意味するのか分かりませんが、あなたのプログラムが今書かれている方法では、 'col_list'は一つの文字列のリストです。 – DyZ

答えて

1

コードからこの行を削除します。

dict1 = dict((k, v.lower()) for k,v in col_list) 

は、それはあなたが内蔵された辞書を上書きループ。