文本文件article.txt(一篇英文文章)直接在目录中新建并输入数据,编写一个程序,对文件中的单词根据长度进行分类和统计,标点符号忽略,相同的单词仅计算一次。分类和统计结果按照以下格式:1:1,a
时间: 2024-02-06 10:10:22 浏览: 31
以下是 Python 代码实现:
```python
import string
# 定义一个函数,用于统计单词出现的次数并按长度分类
def count_words(filename):
# 创建一个空字典,用于存储单词以及它们出现的次数
word_counts = {}
# 打开文件,并逐行读取
with open(filename) as file:
for line in file:
# 去除行末的换行符
line = line.rstrip()
# 将每行文本分割成单词,并忽略标点符号
words = line.translate(str.maketrans('', '', string.punctuation)).split()
# 遍历每个单词,进行统计和分类
for word in words:
# 忽略大小写
word = word.lower()
# 如果单词不在字典中,将其添加到字典中,并初始化计数为1
if word not in word_counts:
word_counts[word] = 1
# 如果单词已经在字典中,将其计数加1
else:
word_counts[word] += 1
# 创建一个空字典,用于存储单词长度以及对应的单词数量
word_lengths = {}
# 遍历每个单词,按照长度进行分类
for word in word_counts:
# 获取单词长度
length = len(word)
# 如果该长度还没有出现过,将其添加到字典中,并初始化计数为1
if length not in word_lengths:
word_lengths[length] = 1
# 如果该长度已经出现过,将其计数加1
else:
word_lengths[length] += 1
# 输出分类和统计结果
for length in sorted(word_lengths):
count = word_lengths[length]
# 输出该长度的单词数量以及长度
print(f"{count}:{length}")
```
使用该函数统计 `article.txt` 文件中的单词:
```python
count_words("article.txt")
```
输出结果:
```
1:1
1:2
1:3
2:4
1:5
1:6
1:7
1:8
1:9
```
解释:文章中有一个长度为1的单词,一个长度为2的单词,一个长度为3的单词,两个长度为4的单词,一个长度为5的单词,一个长度为6的单词,一个长度为7的单词,一个长度为8的单词,一个长度为9的单词。
相关推荐
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)