文本挖掘和词云图绘制

该文展示了使用Python的jieba库进行文本分词,去除停用词,生成词频统计表并制作词云图的过程。通过正则表达式清理文本,加载自定义词库,以及对分词结果的进一步处理,强调了数据预处理在分析中的重要性。
摘要由CSDN通过智能技术生成
# 分词库
import re
import jieba
import pandas as pd
import numpy as np
from PIL import Image
from collections import Counter  # 导入频率统计函数
from wordcloud import WordCloud
# 导入文本
txt = open("../文本分析/黑月光.txt", 'r', encoding='UTF-8').read()
# 使用正则表达式去除文本中所有的换行符和空白符
txt = re.sub('\n+', '', txt)
# 创建新文本
file = open('../文本分析/处理后文本.txt', 'w')
file.write(txt)
# 预处理
# 特殊词
jieba.add_word('藤萝为枝')
# 1.添加词库
# Special_words.txt 是特色词语的路径
jieba.load_userdict('Special_words.txt')

# 2.分词
Words_list = jieba.lcut(txt)  # 进行分词,结果为词语列表
print(len(Words_list))  # 输出词语总数量,结果为 387561
print(Words_list[:10])  # 输出前 10 个词语

# 去除停用词:一些不重要的副词、语助词等
Stopwords = open('../文本分析/stopwords.txt', 'r', encoding='utf-8').readlines()
Stopwords = [word.strip() for word in Stopwords]

# 去除分词库中的停用词
Words_list = [word for word in Words_list if word not in Stopwords]  # 不在停用库中的词
# 去停用词后的总词数
print(len(Words_list))  # 输出:228053, 较去除之前减少了168038个词语

# 按需处理其他词语
# 去除不含中文的词语
Words_list = [word for word in Words_list if bool(re.search('[\u4e00-\u9fa5]', word)) == True]
# 去除字数为 1 的词语
Words_list = [word for word in Words_list if len(word) != 1]
# 去除字数大于3的词语
Words_list = [word for word in Words_list if len(word) <= 4]
# 输出剩余词语的数量
print(len(Words_list))  # 输出:121616,较原始txt减少285277个词语,可见数据预处理的重要性
str1 =",".join(Words_list)
file = open('../文本分析/new.txt', 'w')
file.write(str1)
# 生成词频统计表
Word_count = Counter(Words_list)  # 统计词频,所得结果为Counter对象
Word_count = dict(Word_count)  # 将结果转为字典对象
# print(Word_count): '黎苏苏': 88;'叶夕雾': 217

# 将词频统计结果保存为表格
Table = pd.DataFrame(columns=['词语', '词频'])  # 生成空表
Table['词语'] = list(Word_count.keys())  # 词语字段保存词语
Table['词频'] = list(Word_count.values())  # 词频字段保存词语对应的词频
Table = Table.sort_values(by=['词频'], ascending=False)  # 按照词频降序排序
Table.to_excel('黑月光词频统计表.xlsx', index=False)  # 将结果保存为 excel 表
# 最终:绘制词云图
newtxt=open("../文本分析/new.txt", 'r', encoding='GBK').read()
mask = np.array(Image.open("../文本分析/p1.png"))
wordcloud = WordCloud(background_color="white",
                      width=800,
                      height=600,
                      max_words=50,
                      max_font_size=80,
                      mask=mask,
                      contour_width=3,
                      contour_color='steelblue',
                      font_path="C:\Windows\Fonts\msyh.ttc"
                      ).generate(newtxt)

wordcloud.to_file('词云图.png')

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值