我要对至少一百万字的小说进行中文词频统计,建立网络小说词库,能否提供一个代码?
时间: 2023-05-20 15:01:06 浏览: 81
当然可以,以下是一个Python代码示例:
```python
import jieba
from collections import Counter
def word_count(file_path):
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
words = jieba.cut(content)
counter = Counter(words)
return counter
if __name__ == '__main__':
file_path = 'your_file_path'
counter = word_count(file_path)
print(counter.most_common(100)) # 输出出现频率最高的前100个词
```
你只需要将 `file_path` 替换成你的小说文件路径即可。
相关问题
怎样对一篇同时含有中文和英文的文本进行词频统计并绘制词云图 python代码
以下是对一篇同时含有中文和英文的文本进行词频统计并绘制词云图的 Python 代码:
```
import jieba
from wordcloud import WordCloud
import matplotlib.pyplot as plt
# 读取文本文件
with open('text.txt', 'r', encoding='utf-8') as f:
text = f.read()
# 分词
text = jieba.cut(text)
# 统计词频
word_freq = {}
for word in text:
if word not in word_freq:
word_freq[word] = 1
else:
word_freq[word] += 1
# 生成词云图
wc = WordCloud(background_color='white', width=800, height=600)
wc.generate_from_frequencies(word_freq)
plt.imshow(wc, interpolation='bilinear')
plt.axis('off')
plt.show()
```
上述代码中,我们首先使用 `jieba` 库对文本进行了分词,然后统计每个词的出现频率。最后使用 `wordcloud` 库生成词云图并绘制出来。需要注意的是,在使用 `jieba` 库时需要提前安装并下载中文分词词库。此外,绘制词云图时可以根据需要调整参数,如背景色、大小等。
用python代码实现对一个中文txt文件进行词频统计,即统计每个词出现的次数,并实现次数的由大到小排序
可以使用Python中的collections模块中的Counter函数来实现词频统计,再结合sorted函数进行排序。
以下是一个示例代码:
```python
from collections import Counter
# 读取中文txt文件
with open('your_file_name.txt', 'r', encoding='utf-8') as f:
text = f.read()
# 分词
words_list = text.split()
# 统计词频
word_counts = Counter(words_list)
# 排序
sorted_word_counts = sorted(word_counts.items(), key=lambda x: x[1], reverse=True)
# 输出结果
for word, count in sorted_word_counts:
print(word, count)
```
其中,`your_file_name.txt`为你要统计的中文txt文件的文件名。需要注意的是,分词需要使用相应的中文分词工具,比如jieba分词库。如果没有安装,可以通过`pip install jieba`安装。