三国演义词频统计jieba
时间: 2023-09-10 17:07:57 浏览: 43
好的,我可以使用Python中的jieba库进行中文分词和词频统计。您需要提供三国演义的文本文件,然后我可以为您编写代码进行词频统计。以下是示例代码:
```python
import jieba
from collections import Counter
# 读取文本文件
with open('sanguo.txt', 'r', encoding='utf-8') as f:
text = f.read()
# 使用jieba进行分词
words = jieba.lcut(text)
# 剔除停用词
stopwords = [',', '。', '的', '了', '在', '是', '和', '有', '他', '我', '你', '她']
words = [word for word in words if word not in stopwords]
# 统计词频
word_count = Counter(words)
# 输出前10个出现频率最高的词
for word, count in word_count.most_common(10):
print(word, count)
```
您需要将代码中的`sanguo.txt`替换为您自己的文本文件名。代码首先使用jieba对文本进行分词,然后剔除停用词,最后使用Counter进行词频统计。输出前10个出现频率最高的词。
相关问题
python三国演义词频统计
好的,可以使用Python中的jieba库进行中文分词和词频统计。
首先,需要安装jieba库。可以使用以下命令安装:
```
pip install jieba
```
接下来,我们需要获取《三国演义》的文本。可以从网络上下载《三国演义》的txt文件,或者直接使用以下代码将《三国演义》从项目文件夹中读取出来:
```python
with open('sanguoyanyi.txt', 'r', encoding='utf-8') as f:
content = f.read()
```
接下来,我们可以对文本进行分词。使用jieba库可以很容易地实现:
```python
import jieba
# 分词
words = jieba.lcut(content)
```
接下来,我们可以统计每个词出现的次数:
```python
from collections import Counter
# 统计词频
word_counts = Counter(words)
```
最后,我们可以输出出现频率最高的前10个词语及其出现次数:
```python
# 输出出现频率前10的词语及其出现次数
for word, count in word_counts.most_common(10):
print(word, count)
```
完整代码如下:
```python
import jieba
from collections import Counter
# 读取《三国演义》文本
with open('sanguoyanyi.txt', 'r', encoding='utf-8') as f:
content = f.read()
# 分词
words = jieba.lcut(content)
# 统计词频
word_counts = Counter(words)
# 输出出现频率前10的词语及其出现次数
for word, count in word_counts.most_common(10):
print(word, count)
```
注意,在上述代码中,需要将`sanguoyanyi.txt`文件放在同级目录下。
python三国演义词频统计云图完整代码
当然,我可以给你提供一个Python的代码示例来实现三国演义词频统计云图。首先,你需要安装`jieba`和`wordcloud`这两个库。`jieba`用于中文分词,`wordcloud`用于生成词云图。
以下是一个简单的代码示例:
```python
import jieba
from wordcloud import WordCloud
import matplotlib.pyplot as plt
# 读取文本文件
with open('sanguo.txt', 'r', encoding='utf-8') as f:
text = f.read()
# 使用jieba进行中文分词
words = jieba.lcut(text)
# 统计词频
word_counts = {}
for word in words:
if len(word) > 1: # 过滤掉单个字的词语
word_counts[word] = word_counts.get(word, 0) + 1
# 生成词云图
wordcloud = WordCloud(font_path='simhei.ttf', width=800, height=400, background_color='white')
wordcloud.generate_from_frequencies(word_counts)
# 显示词云图
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')
plt.show()
```
请确保你已经将三国演义的文本文件命名为`sanguo.txt`并与代码文件放在同一目录下。你还需要下载一个中文字体文件(例如`simhei.ttf`)并将其放在代码文件所在目录下,以确保生成的词云图中文显示正常。