用python3写一段代码,使用jieba打开一段txt文件进行分词,再进行词频统计,并将结果逐行写入一个新的txt文件中,再以此为依据使用matplotlib绘图
时间: 2024-03-26 11:34:08 浏览: 16
好的,下面是一段示例代码,其中使用了jieba和matplotlib库:
```python
import jieba
import matplotlib.pyplot as plt
from collections import Counter
# 打开文本文件并读取内容
with open('example.txt', 'r') as f:
text = f.read()
# 使用jieba库进行分词
words = jieba.cut(text)
# 统计词频
freq = Counter(words)
# 将结果写入新的文本文件
with open('result.txt', 'w') as f:
for w, f in freq.items():
f.write(f"{w}\t{f}\n")
# 取出前10个高频词和它们的词频
top_words = freq.most_common(10)
top_words, top_freqs = zip(*top_words)
# 绘制柱状图
plt.bar(top_words, top_freqs)
plt.title('Top 10 Most Frequent Words')
plt.xlabel('Words')
plt.ylabel('Frequency')
plt.show()
```
在这段代码中,我们首先打开了一个名为`example.txt`的文本文件,并使用`jieba`库中的`cut`函数对文本进行了分词处理。然后,我们使用`collections`模块的`Counter`函数统计了每个词出现的次数,并将结果逐行写入了一个名为`result.txt`的新文本文件中。最后,我们使用`matplotlib`库将这些高频词的词频绘制成柱状图。