函数接口定义: def word_count(words) 其中 words 是一个列表,其中的元素为单词字符串。 函数须返回其中每个单词出现的次数,以字典的形式返回。 字典的key是单词,value是单词次数。python
时间: 2023-12-10 14:39:00 浏览: 37
实现word_count函数的代码如下:
```python
def word_count(words):
word_dict = {}
for word in words:
if word in word_dict:
word_dict[word] += 1
else:
word_dict[word] = 1
return word_dict
```
这个函数的实现很简单,我们使用一个字典来统计每个单词出现的次数。对于列表中的每个单词,我们检查它是否已经出现在字典中。如果是,则将该单词对应的值加1;否则,在字典中添加该单词并将其值设置为1。最后,返回字典即可。
相关问题
6-4 Python - 0023 分数 10  全屏浏览题目 作者 樊志伟 单位 许昌学院 统计词频 函数接口定义: def word_count(words) 其中 words 是一个列表,其中的元素为单词字符串。 函数须返回其中每个单词出现的次数,以字典的形式返回。 字典的key是单词,value是单词次数。 裁判测试程序样例: /* 请在这里填写答案 */ words = input().split(" ") result = word_count(words) for key in sorted(list(result.keys())): print(key, result[key]) 输入样例: hello world hello python hello you and me 输出样例: and 1 hello 3 me 1 python 1 world 1 you 1 代码长度限制 16 KB 时间限制 400 ms 内存限制 64 MB
以下是实现 word_count 函数的 Python 代码:
```python
def word_count(words):
result = {}
for word in words:
if word in result:
result[word] += 1
else:
result[word] = 1
return result
```
该函数接收一个列表 words,遍历列表中的每个单词,统计每个单词出现的次数,并将结果存储在字典 result 中,最后返回该字典。注意,当某个单词第一次出现时,需要将其初始次数设为 1。
count_of_words()函数统计read_file()函数返回的字符串中的单词数量和不重复的单词数量。
以下是一个示例实现:
```python
def read_file(filename):
with open(filename, 'r') as file:
text = file.read()
return text
def count_of_words(text):
# 将所有非字母替换为空格,然后将字符串拆分为单词列表
words = text.lower().replace('[^a-zA-Z]', ' ').split()
# 统计单词数量和不重复单词数量
word_count = len(words)
unique_words = set(words)
unique_word_count = len(unique_words)
return word_count, unique_word_count
```
这里使用了正则表达式来将所有非字母字符替换为空格,然后使用 `split()` 方法将字符串拆分为单词列表。然后,使用 Python 的 `set()` 数据类型来获取不重复的单词,并统计单词数量和不重复单词数量。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)