python四大名著词频统计代码
时间: 2023-10-13 22:27:29 浏览: 42
以下是Python中四大名著的词频统计代码:
```python
import jieba
from collections import Counter
# 读取文本文件
with open('shuihu.txt', 'r', encoding='utf-8') as f:
text = f.read()
# 分词
words = jieba.cut(text)
# 去除停用词
stop_words = set()
with open('stopwords.txt', 'r', encoding='utf-8') as f:
for line in f:
stop_words.add(line.strip())
words = [word for word in words if word not in stop_words]
# 统计词频
counter = Counter(words)
# 输出前10个高频词
for word, count in counter.most_common(10):
print(word, count)
```
其中,`jieba`是中文分词库,需要先安装;`stopwords.txt`是停用词表,可以根据需要自行添加或删除词语。
相关问题
四大名著人物统计python
以下是使用Python统计四大名著人物出现次数的示例代码:
```python
import jieba
# 读取文本文件
with open('journey_to_the_west.txt', 'r', encoding='utf-8') as f:
text = f.read()
# 使用jieba分词进行中文分词
words = jieba.lcut(text)
# 统计人物出现次数
counts = {}
for i in range(len(words)-1):
if words[i] == '孙悟空' or words[i] == '唐僧' or words[i] == '猪八戒' or words[i] == '沙和尚':
if words[i+1] != ',' and words[i+1] != '。' and words[i+1] != '!' and words[i+1] != '?':
name = words[i]
counts[name] = counts.get(name, 0) + 1
# 输出结果
for name in counts:
print(name, counts[name])
```
在这个示例代码中,我们首先使用`jieba`进行中文分词,然后遍历分词结果,统计人物出现次数。四大名著中的主要人物包括孙悟空、唐僧、猪八戒和沙和尚,因此我们在遍历过程中判断每个词语是否为其中一个人物的名字,如果是,就将其后面的词语作为该人物的出现场景,统计出现次数。最后输出结果,得到每个人物的出现次数。
python西游记词频统计代码
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等第三方库。这些库提供了更强大的文本处理功能,可以帮助你更好地完成类似的任务。