使用Python中的csv文件,使用字典计算字符串中的字数

使用Python中的csv文件,使用字典计算字符串中的字数,python,string,csv,dictionary,count,Python,String,Csv,Dictionary,Count,我有一个从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

我有一个从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

像这样的怎么样:

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())

您能修复缩进吗?dict_1和字符串之前无法定义,它们必须能够输入。好的,请将代码重写为函数:
def matches(dict_,str_):…