2016-12-19 21 views
3

csvファイルから辞書を返すコードがあります。これで、任意の文字列に含まれる単語の数を数えたいと思います。例えば、もしI入力:Pythonでcsvファイルを使用して辞書を使用して文字列内の単語数をカウントする

「どのように多くの言葉この文字列ではdict1からです」

どうだろう、私、この文字列をループし、文字列で表示されますdict1から単語を数えますか?

コード:

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.""" 

    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 
+0

あなたのインデントを修正していただけますか? – 2ps

答えて

0

どのようにこのようなものについて:

str_ = "How many words in this string are from dict1" 
dict_1 = dict(a='many', b='words') 

# With list comprehension 

len([x for x in str_.split() if x in dict_1.values()]) 
# 2 

# These ones don't count duplicates because they use sets 

len(set(str_.split()).intersection(dict_1.values())) 
# 2 
len(set(str_.split()) & set(dict_1.values())) # Equivalent, but different syntax 
# 2 

# To be case insensitive, do e.g., 
words = str_.lower().split() 
dict_words = map(str.lower, dict_1.values()) 
+0

dict_1文字列を事前に定義することはできません。入力できる必要があります。 – Suzaku

+0

OK、関数としてコードを書き直してください: 'def matches(dict_、str_):...' – innisfree

関連する問題