python读取文本文件,生成词云图
更改当前工作目录为脚本所在的目录
去除标点符号和停用词
添加过滤单字的逻辑
生成概览总结
提高词云图的清晰度
黑体字
txt生成词云
《厚黑学》-李宗吾_着.png
代码如下:
from pathlib import Path
# 获取当前脚本的路径对象
script_path = Path(__file__).resolve()
# 获取脚本所在的目录
script_dir = script_path.parent
# 更改当前工作目录为脚本所在的目录
import os
os.chdir(script_dir)
import jieba
import numpy as np
from PIL import Image
from wordcloud import WordCloud, ImageColorGenerator
import matplotlib.pyplot as plt
from collections import Counter
import re
import chardet
from pathlib import Path
# 读取文本文件
def read_txt_file(file_path):
with open(file_path, 'rb') as file:
raw_data = file.read()
result = chardet.detect(raw_data)
encoding = result['encoding']
try:
with open(file_path, 'r', encoding=encoding) as file:
text = file.read()
except UnicodeDecodeError:
with open(file_path, 'r', encoding=encoding, errors='ignore') as file:
text = file.read()
return text
# 中文分词
def chinese_word_segmentation(text):
return jieba.lcut(text)
# 去除标点符号和停用词
def remove_punctuation_and_stopwords(words, stopwords):
return [word for word in words if word not in stopwords and re.match(r'[\u4e00-\u9fffA-Za-z]', word)]
# 生成概览总结
def generate_summary(word_freq, top_n=10):
top_words = word_freq.most_common(top_n)
summary = [word for word, freq in top_words]
return ' '.join(summary)
# 为了提高词云图的清晰度,我们可以在生成 WordCloud 对象时设置更高的分辨率。
# 可以通过设置 `width` 和 `height` 参数来增加词云图的尺寸,同时设置 `dpi` 参数来提高图像的分辨率。
# 确保在 main 函数中调用修改后的 generate_wordcloud 函数
def main():
file_path = '《厚黑学》-李宗吾_着.txt' # 替换为你的文本文件路径
stopwords_path = 'stopwords.txt' # 替换为你的停用词文件路径
font_path = r'C:\Windows\Fonts\simhei.ttf' # 黑体字体路径
background_image_path = None # 背景图片路径,可选
try:
# 读取文本
text = read_txt_file(file_path)
except FileNotFoundError:
print(f"错误:文件 {file_path} 未找到。请检查文件路径。")
return
try:
# 读取停用词
stopwords = set(read_txt_file(stopwords_path).split())
except FileNotFoundError:
print(f"错误:文件 {stopwords_path} 未找到。请检查文件路径。")
return
# 中文分词
words = chinese_word_segmentation(text)
# 去除标点符号和停用词
filtered_words = remove_punctuation_and_stopwords(words, stopwords)
# 这里添加过滤单字的逻辑
filtered_words = [word for word in filtered_words if len(word) > 2]
# 生成词云
word_freq = generate_wordcloud(filtered_words, font_path, file_path, background_image_path)
# 生成概览总结
summary = generate_summary(word_freq)
print("概览总结:", summary)
# 为了将生成的高清图片保存到同文件夹下,文件名同txt文件名,我们需要修改 generate_wordcloud 函数。
# 首先,我们需要从文件路径中提取文件名,然后使用该文件名来保存图片。
# 修改 generate_wordcloud 函数
def generate_wordcloud(words, font_path, file_path, background_image_path=None):
if background_image_path:
background_image = np.array(Image.open(background_image_path))
image_colors = ImageColorGenerator(background_image)
# 设置更高的分辨率
wc = WordCloud(font_path=font_path, background_color="white", max_words=2000, mask=background_image,
color_func=image_colors, width=3000, height=1500)
else:
# 设置更高的分辨率
wc = WordCloud(font_path=font_path, background_color="white", max_words=2000, width=3000, height=1500)
word_freq = Counter(words)
wc.generate_from_frequencies(word_freq)
plt.figure(figsize=(10, 5), dpi=600) # 设置 matplotlib 图形的分辨率
plt.imshow(wc, interpolation='bilinear')
plt.axis("off")
# 从文件路径中提取文件名
file_name = Path(file_path).stem
# 保存图片到同文件夹下,文件名同txt文件名
wc.to_file(f'{file_name}.png')
plt.show()
return word_freq
if __name__ == "__main__":
main()