import jieba
import re
from collections import Counter
# 加载停用词列表,创建停用词集合
with open(r'stopwords\四大停用词.txt', 'r', encoding='utf-8') as f:
stopwords = set([line.strip() for line in f.readlines()])
text = open('朱自清春.txt', 'r').read()
def clean_text(text):
cleaned_text = re.sub(r'[\s\r\n]+', ' ', text) # 将多个空格,回车符和换行符替换为单个空格
cleaned_text = re.sub(r'\u3000', ' ', cleaned_text) # 全角空格转为半角
cleaned_text = re.sub(r"[^a-zA-Z0-9\u4e00-\u9fa5]+", "", cleaned_text) #只保留中英文数字
return cleaned_text.strip()
cleaned_text = clean_text(text)
seg_list = jieba.lcut(cleaned_text, cut_all=False)
# 过滤停用词
filtered_seg_list = [word for word in seg_list if word not in stopwords]
# 统计词频
#word_counts = Counter(filtered_seg_list)
# 打印词频统计结果
# for word, freq in word_counts.items():
# print(f"'{word}': {freq}")
# 统计词频并获取前30个高频词汇
top_30_words = Counter(filtered_seg_list).most_common(30)
# 打印词频统计结果
for word, freq in top_30_words:
print(f"'{word}': {freq}")
结果为
'春天': 4
'里': 4
'盼望着': 2
'小草': 2
'大片': 2
'满是': 2
'不让': 2
'花': 2
'赶趟儿': 2
'眼': 2
'名字': 2
'眨': 2
'新': 2
'走': 2
'东风': 1
'脚步': 1
'睡醒': 1
'样子': 1
'欣欣然': 1
'张开': 1
'眼山朗润': 1
'水': 1
'涨起来': 1
'太阳': 1
'脸红': 1
'偷偷地': 1
'土里': 1
'钻出来': 1
'嫩嫩的': 1
'绿绿的': 1
制作词云图
#词云图制作
from wordcloud import WordCloud #词云图
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
# 读取图片文件作为词云的形状模板
mask_image = Image.open('rocket.png') # 图片遮罩
mask_np = np.array(mask_image)
# 生成词云对象,设置词云属性并使用mask参数
# 注意:这里需要指定支持中文的字体路径,否则词云可能无法显示中文
wordcloud = WordCloud(font_path='simhei.ttf', background_color="white", mask=mask_np).generate_from_frequencies(dict(top_30_words))
# 显示词云图
plt.figure(figsize=(12, 8)) #以英寸为单位
plt.imshow(wordcloud, interpolation='bilinear') #plt.imshow函数用于在图形窗口中显示图像,interpolation='bilinear'设置了插值方法
plt.axis("off") #关闭图形的坐标轴
plt.show() #在屏幕上显示图形窗口
所用遮罩图
效果图: