python西游记词频统计代码
时间: 2024-05-13 18:11:46 浏览: 14
Python西游记词频统计代码可以用Python的内置库collections来实现。以下是一个简单的示例:
```
import collections
# 读取文件内容
with open('journey_to_the_west.txt', 'r', encoding='utf-8') as f:
content = f.read()
# 统计词频
words = content.split()
word_counts = collections.Counter(words)
# 输出前10个高频词
for word, count in word_counts.most_common(10):
print(word, count)
```
在这个代码中,我们使用了Python内置的Counter类来统计词频。首先,我们打开journey_to_the_west.txt文件,并将其内容读取到content变量中。然后,我们将content按照空格划分为单词,并使用Counter统计单词出现的次数。最后,我们使用most_common方法找出出现次数最多的前10个单词,并将它们输出到屏幕上。
如果你想要深入学习Python的文本处理功能,我建议你学习Python的nltk和spaCy等第三方库。这些库提供了更强大的文本处理功能,可以帮助你更好地完成类似的任务。
相关问题
python西游记词频统计
以下是Python实现《西游记》词频统计的代码和步骤:
1. 读取《西游记》文本文件
```python
with open('xyj.txt', 'r', encoding='utf-8') as f:
text = f.read()
```
2. 使用正则表达式去除文本中的非汉字字符
```python
import re
text = re.sub('[^\u4e00-\u9fa5]', '', text)
```
3. 统计每个汉字出现的次数
```python
from collections import Counter
counter = Counter(text)
```
4. 统计不同汉字的个数
```python
num_unique_chars = len(counter)
```
5. 找出出现次数最多的前10个汉字
```python
most_common = counter.most_common(10)
```
6. 将结果保存到json文件中
```python
import json
result = {
'num_unique_chars': num_unique_chars,
'most_common': most_common,
'counter': dict(counter)
}
with open('result.json', 'w', encoding='utf-8') as f:
json.dump(result, f, ensure_ascii=False, indent=4)
```
西游记文本词频统计,词云图的制作代码
以下是一个简单的实现文本词频统计和词云图制作的Python代码,你可以根据需要进行修改:
```python
# 导入需要的库
import jieba
from wordcloud import WordCloud
from collections import Counter
from PIL import Image
import numpy as np
# 读取文本文件
with open('西游记.txt', 'r', encoding='utf-8') as f:
content = f.read()
# 使用jieba分词
words = jieba.cut(content)
# 统计词频
word_counts = Counter(words)
# 生成词云图
mask = np.array(Image.open('yuanbao.jpg')) # 词云图形状
wordcloud = WordCloud(
font_path='msyh.ttc', # 字体文件路径
background_color='white', # 背景颜色
mask=mask, # 词云图形状
width=800, height=600 # 图片大小
)
wordcloud.generate_from_frequencies(word_counts)
# 保存词云图
wordcloud.to_file('wordcloud.png')
```
其中,'西游记.txt'是要统计词频的文本文件路径,'yuanbao.jpg'是词云图形状的图片文件路径,'msyh.ttc'是使用的字体文件路径。生成的词云图将保存在'wordcloud.png'文件中。你可以根据需要修改这些参数。