利用python统计英语6级试题(第3次实验中提供的artical.txt)中所有单词的词频,并将统计的单词按照出现频次从高到底的顺序存储至Excel文件words.xlsx(或words.xls)的Sheet1工作表中。
时间: 2024-03-16 12:42:04 浏览: 17
以下是实现该功能的Python代码:
```python
import openpyxl
from collections import Counter
# 读取文章内容
with open('artical.txt', 'r', encoding='utf-8') as f:
content = f.read()
# 去除标点符号和换行符
content = content.replace('\n', ' ')
for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~':
content = content.replace(ch, '')
# 将文章中的单词按照出现频次从高到低排序
words = content.split()
word_count = Counter(words)
sorted_words = sorted(word_count.items(), key=lambda x: x[1], reverse=True)
# 将排序后的单词存储至Excel文件
wb = openpyxl.Workbook()
ws = wb.active
ws.title = 'Sheet1'
ws['A1'] = '单词'
ws['B1'] = '词频'
for i, (word, count) in enumerate(sorted_words):
ws.cell(row=i+2, column=1, value=word)
ws.cell(row=i+2, column=2, value=count)
wb.save('words.xlsx')
```
运行该代码后,会在当前目录下生成一个名为`words.xlsx`的Excel文件,并在其中的`Sheet1`工作表中存储排序后的单词及其词频。