统计词频。要求:输入为一系列空格分隔的单词,输出单词及单词出现的次数\n",
时间: 2024-05-10 17:19:26 浏览: 19
可以使用 Python 来实现。
首先,我们需要输入一系列空格分隔的单词,并将其存储在一个字符串中。然后,我们可以使用 split() 方法将字符串拆分为一个单词列表。接下来,我们可以使用 Python 的字典(dict)来记录每个单词出现的次数。最后,我们可以遍历字典并输出每个单词及其出现的次数。
下面是完整的 Python 代码示例:
```python
# 输入一系列空格分隔的单词
words = input("请输入一系列空格分隔的单词:")
# 将字符串拆分为一个单词列表
word_list = words.split()
# 使用字典记录每个单词出现的次数
word_count = {}
for word in word_list:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
# 遍历字典并输出每个单词及其出现的次数
print("单词\t出现次数")
for word, count in word_count.items():
print(f"{word}\t{count}")
```
示例输出:
```
请输入一系列空格分隔的单词:apple banana apple orange banana
单词 出现次数
apple 2
banana 2
orange 1
```
相关问题
python编程实现英文词频统计:文件words.txt,读取文件中内容,要求统计文件中英文单词的个数,输出单词及出现次数。
好的,可以使用Python的正则表达式和字典来实现英文词频统计。具体代码如下:
```python
import re
# 读取文件内容
with open("words.txt", "r") as f:
content = f.read()
# 使用正则表达式匹配所有英文单词
words = re.findall(r'\b[A-Za-z]+\b', content)
# 统计每个单词出现的次数
word_count = {}
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
# 输出单词及出现次数
for word, count in word_count.items():
print(f"{word}: {count}")
```
其中,`re.findall(r'\b[A-Za-z]+\b', content)` 用来匹配所有由英文字母组成的单词,并将其存储在一个列表中。接着,使用字典来统计每个单词出现的次数,最后输出每个单词及其出现次数。
输入一行文本统计不同单词的词频,使用字典
好的,我可以给你一个Python代码示例,用于统计文本中不同单词的出现次数:
```python
text = input("请输入一行本:")
words = text.split() # 将文本按空格分割成单词列表
freq_dict = {}
for word in words:
if word in freq_dict:
freq_dict[word] += 1 # 如果单词已在字典中,则将其出现次数+1
else:
freq_dict[word] = 1 # 如果单词不在字典中,则将其添加到字典并设置出现次数为1
# 输出结果
print("不同单词的词频:")
for word, freq in freq_dict.items():
print(word, ":", freq)
```
你可以运行这个代码,并输入一行文本来测试它。它将统计文本中每个不同单词的出现次数,并输出每个单词及其出现次数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)