Chapter 2.1 高频词和关键词提取(一)

知识点2.1.1 高频词和关键词的区别

高频词:在文档中出现频数较高的词

关键词:能够代表文档重要内容的词

知识点2.1.2 基于numpy和pandas的高频词提取

#载入需要的程序包
import numpy as np
import pandas as pd
import jieba
#导入需分析的文档,并查看前10行
chap2 = pd.read_csv('C:\\Users\\dell-pc\\desktop\\2021.txt', names = ['txt'], sep = '\t', encoding = 'utf-8')
chap2.head(10)
#导入自定义的新词词典
newword = 'C:\\Users\\dell-pc\\desktop\\新词.txt'
jieba.load_userdict(newword)
#导入自定义的停用词词典
stopword = pd.read_csv('C:\\Users\\dell-pc\\desktop\\停用词.txt', names = ['stopword'], sep = '\t', encoding = 'utf-8')
#使用jieba.cut命令进行分词,并去除停用词和长度小于1的字符串
word_list = [word for word in jieba.cut(" ".join(chap2.txt)) if word not in list(stopword.stopword)] 
word_list = [x.strip() for x in word_list if len(x.strip()) > 1]
print(word_list)
#查看分词结果的个数
dimen = np.array(word_list).shape
print(dimen)
#将分词结果的类型转为数据框,并查看前10行
word_df = pd.DataFrame(word_list, columns = ['word'])
word_df.head(10)
#按不同词进行分组,并分组统计元素个数
word_freq = word_df.groupby(['word']).size()
#将分组统计结果按降序排列,并查看前10行
freq_list = word_freq.sort_values(ascending = False)
freq_list[:10]
#查看某个词的频数
freq_list['高质量']

知识点2.1.3 基于nltk的高频词提取

#安装nltk包
pip install nltk
#载入nltk包
import nltk
#统计分词结果的词频(形成词频词典),并查看前10行
freq_dic = nltk.FreqDist(word_list)
freq_dic.most_common(10)
#查看某个词的频数
freq_dic['高质量']

知识点2.1.4 高频词的词云图展示

#安装wordcloud包
pip install wordcloud
#载入需要的程序包
import wordcloud
import matplotlib.pyplot as plt
#导入需要的中文字体
myfont = r'C:\Windows\Fonts\msyhbd.ttc'
#绘制词云图
word_cloud = wordcloud.WordCloud(font_path = myfont,
                                 width = 1200,
                                 height = 800,
                                 mode = 'RGBA',
                                 background_color = None,
                                 max_words = 50,
                                 colormap = 'cividis').fit_words(freq_list)
  • font_path 设置自定义字体路径
  • width 设置图片宽度,默认为400
  • height 设置图片高度,默认为200
  • mode 默认为‘RGB’,当设置为’RGBA’时背景色为透明
  • background_color 设置图片背景色,默认为黑色
  • max_words 设置图片显示的词数,默认为200
  • colormap 设置字体颜色

wordcloud官方网址(https://amueller.github.io/word_cloud/)

字体颜色参考网址(https://matplotlib.org/stable/gallery/color/colormap_reference.html)

#展示词云图
plt.imshow(word_cloud)
plt.axis("off")
plt.show() 
#保存词云图
word_cloud.to_file("chap201.png")

欢迎关注微信公众号“Trihub数据社”

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值