31. (资料题, 10.0分) 完成下列代码,实现一个函数 count_words,接受一个字符串str作为参数,统计该字符串中每个单 词出现的次数,并以字典的形式返回结果。假设该字符串中只包含小写字母和空格,且不以空格开头 或结尾。 def count_words(str): word_dict = (1) for word in (2) : if word in word_dict: word_dict[word] += (3) else: word_dict[word] = (4) return (5) str = "the quick brown fox jumps over the lazy dog" print(count_words(str))
时间: 2024-02-28 13:57:07 浏览: 95
完成代码如下:
```
def count_words(str):
word_dict = {}
for word in str.split():
if word in word_dict:
word_dict[word] += 1
else:
word_dict[word] = 1
return word_dict
str = "the quick brown fox jumps over the lazy dog"
print(count_words(str))
```
输出结果为:
```
{'the': 2, 'quick': 1, 'brown': 1, 'fox': 1, 'jumps': 1, 'over': 1, 'lazy': 1, 'dog': 1}
```
阅读全文
相关推荐












