使用jieba库 假设有一个年度工作报告的文本文件(in.txt)。实现数据统计功能:统计文件中出现次数最多的10个词语和相应的出险次数,作为主题词,要求词语不少于2个字符。 统计结果写入文件out.txt Python
时间: 2023-07-16 20:17:13 浏览: 78
以下是使用Python和jieba库实现数据统计功能的代码:
```python
import jieba
from collections import Counter
# 读取文件内容
with open('in.txt', 'r', encoding='utf-8') as f:
content = f.read()
# 分词并统计词频
words = []
for word in jieba.cut(content):
if len(word) >= 2:
words.append(word)
word_counts = Counter(words)
# 获取出现次数最多的前10个词语
top_10_words = word_counts.most_common(10)
# 写入文件
with open('out.txt', 'w', encoding='utf-8') as f:
for word, count in top_10_words:
f.write(word + '\t' + str(count) + '\n')
```
该代码首先使用jieba库对文本进行分词,并统计每个词语出现的次数。然后,使用collections库的Counter类对词频进行统计,并获取出现次数最多的前10个词语。最后,将结果写入文件out.txt中,每行一个词语和相应的出现次数,用制表符分隔。
相关问题
使用jieba库 假设有一个年度工作报告的文本文件(in.txt)。实现数据统计功能:统计文件中出现次数最多的10个词语,作为主题词,要求词语不少于2个字符。 统计结果写入文件out.txt Python
可以使用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()函数按词频从大到小排序,再取前五个即为出现次数最多的五个词。