【发布时间】: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