使用jieba库 假设有一个年度工作报告的文本文件(in.txt)。实现数据统计功能:统计文件中出现次数最多的10个词语,作为主题词,要求词语不少于2个字符。 统计结果写入文件out.txt Python
时间: 2023-07-16 13:17:08 浏览: 64
可以使用Python中的jieba库和collections库来完成这个任务。
首先需要安装jieba库,可以使用以下命令安装:
```
pip install jieba
```
然后,可以按照以下步骤来实现数据统计功能:
1. 读取文本文件并进行分词
2. 统计每个词语出现的次数
3. 找到出现次数最多的10个词语
4. 将统计结果写入文件out.txt
下面是完整的代码:
```python
import jieba
from collections import Counter
# 读取文件
with open('in.txt', 'r', encoding='utf-8') as f:
text = f.read()
# 分词
words = jieba.cut(text)
# 统计词频
word_counts = Counter(words)
# 找到出现次数最多的10个词语
top_words = [word for word, count in word_counts.most_common(10) if len(word) >= 2]
# 将统计结果写入文件out.txt
with open('out.txt', 'w', encoding='utf-8') as f:
f.write('\n'.join(top_words))
```
这个代码会将出现次数最多的10个词语写入文件out.txt中,每行一个词语。
相关问题
用jieba库对文件分词并统计出现次数最多的五个词
好的,首先需要安装jieba库,可以使用以下命令安装:
```
pip install jieba
```
然后,我们可以使用以下代码来对文件进行分词并统计出现次数最多的五个词:
```python
import jieba
# 打开文件并读取内容
with open('example.txt', 'r', encoding='utf-8') as f:
content = f.read()
# 对内容进行分词
words = jieba.lcut(content)
# 统计词频
word_counts = {}
for word in words:
if len(word) == 1 or word == '\r\n':
continue
else:
word_counts[word] = word_counts.get(word, 0) + 1
# 按词频排序并取前五个
top_five = sorted(word_counts.items(), key=lambda x: x[1], reverse=True)[:5]
# 输出结果
for word, count in top_five:
print(f'{word}: {count}')
```
其中,假设待分词的文件名为example.txt,代码中读取文件内容后使用jieba.lcut()函数对内容进行分词,然后使用一个字典word_counts记录每个词出现的次数。最后使用sorted()函数按词频从大到小排序,再取前五个即为出现次数最多的五个词。
读取 data.txt 文件并借助 jieba 库实现词频统计, 将出现频率最高的 10 个词输出
好的,我可以帮你实现这个功能。首先需要安装`jieba`库,可以使用以下命令进行安装:
```
pip install jieba
```
然后我们可以编写以下代码读取`data.txt`文件并进行词频统计:
```python
import jieba
# 读取文件内容
with open('data.txt', 'r', encoding='utf-8') as f:
content = f.read()
# 进行分词
words = jieba.cut(content)
# 统计词频
word_count = {}
for word in words:
if len(word) > 1: # 只统计长度大于1的词
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
# 输出出现频率最高的前10个词
top_words = sorted(word_count.items(), key=lambda x: x[1], reverse=True)[:10]
for word, count in top_words:
print(word, count)
```
以上代码首先使用`open()`函数读取`data.txt`文件的内容,然后使用`jieba.cut()`函数对内容进行分词。接着使用一个字典`word_count`统计每个词出现的次数,最后使用`sorted()`函数对字典进行排序,输出出现频率最高的前10个词。