利用python程序读取文件内容,统计出出现频率最高的7个单词,并按照从大到小的顺序进行输出
时间: 2024-02-27 11:58:57 浏览: 44
好的,以下是一个简单的Python程序,可以实现你的需求:
```python
import re
from collections import Counter
# 读取文件内容
with open('file.txt', 'r') as f:
text = f.read()
# 使用正则表达式去除标点符号和换行符
text = re.sub('[^\w\s]', ' ', text)
text = re.sub('\n', ' ', text)
# 将字符串按照空格分割成单词列表
words = text.split()
# 统计单词出现次数
word_counts = Counter(words)
# 获取出现频率最高的7个单词
top_words = word_counts.most_common(7)
# 按照从大到小的顺序输出
for word, count in sorted(top_words, key=lambda x: x[1], reverse=True):
print(word, count)
```
你只需要将文件名 `file.txt` 替换成你要处理的文件名,然后运行该程序即可。
相关问题
Python读取文本文件的内容 统计其频率最高的10个单词,将结果写入csv文件中
好的,您可以尝试以下代码:
```python
import csv
from collections import Counter
# 读取文本文件
with open('your_file.txt', 'r') as file:
text = file.read().lower()
# 将文本转换成单词列表
words = text.split()
# 使用Counter对单词列表计数
word_counts = Counter(words)
# 取出现次数最高的前10个单词
top_words = word_counts.most_common(10)
# 将结果写入csv文件
with open('result.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['word', 'count'])
for word, count in top_words:
writer.writerow([word, count])
```
需要替换掉 `your_file.txt` 和 `result.csv` 为你实际的文件名。另外,这里使用了Python的`collections`模块中的`Counter`类进行单词计数,可以方便地统计出现次数。
Python读取文本文件中的内容 统计其频率最高的10个单词,将结果写入csv文件中
好的,您可以尝试以下代码:
```python
import csv
# 读取文本文件
with open('your_file.txt', 'r') as file:
text = file.read().lower()
# 将文本转换成单词列表
words = text.split()
# 统计每个单词出现的次数
word_counts = {}
for word in words:
if word in word_counts:
word_counts[word] += 1
else:
word_counts[word] = 1
# 按照出现次数排序
sorted_word_counts = sorted(word_counts.items(), key=lambda x: x[1], reverse=True)
# 取出现次数最高的前10个单词
top_words = sorted_word_counts[:10]
# 将结果写入csv文件
with open('result.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['word', 'count'])
for word, count in top_words:
writer.writerow([word, count])
```
需要替换掉 `your_file.txt` 和 `result.csv` 为你实际的文件名。