【问题标题】:Count the number of words in a string by using a dictionary using a csv file in Python使用Python中的csv文件使用字典来计算字符串中的单词数
【发布时间】: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


【解决方案1】:

这样的事情怎么样:

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 和字符串不能预先定义,它们必须能够输入。
  • OK,所以将代码重写为函数:def matches(dict_, str_): ...
猜你喜欢
  • 1970-01-01
  • 2023-03-03
  • 2011-09-26
  • 2020-05-20
  • 1970-01-01
  • 1970-01-01
  • 2014-09-10
  • 2013-05-24
  • 1970-01-01
相关资源
最近更新 更多