Python 字符串到字典的字数

Python 字符串到字典的字数,python,python-3.x,dictionary,word-frequency,Python,Python 3.x,Dictionary,Word Frequency,所以我有一个家庭作业问题 编写一个函数词计数器(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 = {}

所以我有一个家庭作业问题

编写一个函数词计数器(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\u counter(“这是一个句子”)
运行代码时,我得到了以下结果:

[('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'
回溯(最近一次呼叫最后一次):
文件“”,第2行,在
builtins.AttributeError:“list”对象没有属性“items”

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

找出了我做错的地方。只需删除最后2行代码并返回计数字典。测试代码完成了其余的工作:)

看起来您在原始代码中找到了错误,因此您可能会得到全部的处理

也就是说,您可以通过使用来收紧代码。文档中的示例与您的任务非常匹配:

>>> # 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)]

sorted
返回列表对象而不是字典对象。因此,
word\u counter
也返回了一个列表对象,您试图在其上调用
items
,就像在字典上调用它一样。这就是问题所在。只需执行
print(word\u counter(“这是一个句子”))
这就是你的函数返回的不是dict而是元组列表,这是dict.items在Python 2中给你的。@Theourtheye我理解我现在对排序和项位的错误,但是,你所说的“只需执行print(word\u counter(“这是一个句子”)”是什么意思这是函数中我唯一需要的东西吗?Sorry@thefourtheye没关系,我只是添加了不必要的代码。他们在测试中完成了我代码的最后两行。哈哈谢谢堆:)