【发布时间】:2017-05-04 01:57:45
【问题描述】:
我有一个代码,它从 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
【问题讨论】:
-
你能修正你的缩进吗?
标签: python string csv dictionary count