【问题标题】:String to Dictionary Word Count字符串到字典字数
【发布时间】:2015-05-24 04:12:31
【问题描述】:

所以我在做作业题时遇到了麻烦。

编写一个函数 word_counter(input_str),它接受一个字符串 input_str 并返回一个字典,将 input_str 中的单词映射到它们的出现次数。

所以我目前的代码是:

def word_counter(input_str):

'''function that counts occurrences of words in a string'''

    sentence = input_str.lower().split()

    counts = {}

    for w in sentence:
        counts[w] = counts.get(w, 0) + 1

    items = counts.items()
    sorted_items = sorted(items)

    return sorted_items

现在,当我在 Python shell 中使用 word_counter("This is a sentence") 之类的测试用例运行代码时,我得到以下结果:

[('a', 1), ('is', 1), ('sentence', 1), ('this', 2)]

这是必需的。但是,用于检查答案的测试代码是:

word_count_dict = word_counter("This is a sentence")
items = word_count_dict.items()
sorted_items = sorted(items)
print(sorted_items)

当我使用该代码运行它时,我得到了错误:

Traceback (most recent call last):
File "<string>", line 2, in <fragment>
builtins.AttributeError: 'list' object has no attribute 'items'

不确定如何更改我的代码以使其与给定的测试代码一起使用。

【问题讨论】:

  • sorted 返回一个列表对象而不是字典对象。所以word_counter 也返回了一个列表对象,你试图在它上面调用items,就像你在字典上调用它一样。那就是问题所在。只要做print(word_counter("This is a sentence"))就够了
  • 你的函数不是返回一个字典,而是一个元组列表,这是 dict.items 在 Python 2 中为你提供的。
  • @thefourtheye 我明白我现在对 sorted 和 items 位做错了什么,但是,“只需执行 print(word_counter("This is a sentence"))”是什么意思我唯一需要的功能是什么?对不起
  • @thefourtheye 没关系,我只是添加了不必要的代码。他们在测试中完成了我代码的最后两行。哈哈谢谢一堆:)

标签: python python-3.x dictionary word-frequency


【解决方案1】:

看来你在原始代码中发现了错误,所以你可能会被照顾。

也就是说,您可以使用collections.Counter() 收紧代码。文档中的示例与您的任务非常匹配:

>>> # Find the ten most common words in Hamlet
>>> import re
>>> words = re.findall(r'\w+', open('hamlet.txt').read().lower())
>>> Counter(words).most_common(10)
[('the', 1143), ('and', 966), ('to', 762), ('of', 669), ('i', 631),
 ('you', 554),  ('a', 546), ('my', 514), ('hamlet', 471), ('in', 451)]

【讨论】:

    【解决方案2】:

    弄清楚我做错了什么。只需删除最后两行代码并返回 counts 字典。测试代码完成其余的工作:)

    【讨论】:

      猜你喜欢
      • 2013-03-17
      • 2023-02-10
      • 2012-10-11
      • 2019-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多