Python implements word frequency statistics and display

How to quickly lock the core content of an article can initially use the most frequently occurring words in the article as the core of the article. Is there any way to display it quickly?
Here is an AI article as a test file, and the test results are shown in the figure:
Insert picture description here

1. To achieve this effect, you first need to install python first, and then you need to install the following plug-ins on your computer:
pip install re # 正则表达式库
pip install collections # 词频统计库
pip install numpy  # numpy数据处理库
pip install jieba  # 结巴分词
pip install wordcloud # 词云展示库
pip install PIL   # 图像处理库
pip install matplotlib.pyplot # 图像展示库
2. Prepare the file you plan to count, name it TestTxt.txt, and save it in the same directory as the program file
3. Prepare a background picture, name it wordcloud.jpg, and save it in the same directory as the program file, as shown below:

Insert picture description here
Next, write the code:

# 导入扩展库
import re # 正则表达式库
import collections # 词频统计库
import numpy as np # numpy数据处理库
import jieba # 结巴分词
import wordcloud # 词云展示库
from PIL import Image # 图像处理库
import matplotlib.pyplot as plt # 图像展示库
from pylab import mpl # 用于处理中文乱码

# 读取文件
fn = open('TestTxt.txt', encoding='utf-8-sig') # 打开文件并编码
string_data = fn.read() # 读出整个文件
fn.close() # 关闭文件

# 文本预处理
pattern = re.compile(u'\t|\n|\.|-|:|;|\)|\(|\?|"') # 定义正则表达式匹配模式
string_data = re.sub(pattern, '', string_data) # 将符合模式的字符去除

# 文本分词
seg_list_exact = jieba.cut(string_data, cut_all = False) # 精确模式分词
object_list = []
remove_words = [u'的', u',',u'和', u'是', u'随着', u'对于', u'对',u'等',u'能',u'都',u'。',u' ',u'、',u'中',u'在',u'了',
                u'通常',u'如果',u'我们',u'需要', u'把', u'但', u'?',u'!', u'...',u'有',u'做',u'大',u'一个',u'一些',u':'] # 自定义去除词库

for word in seg_list_exact: # 循环读出每个分词
    if word not in remove_words: # 如果不在去除词库中
        object_list.append(word) # 分词追加到列表

# 词频统计
word_counts = collections.Counter(object_list) # 对分词做词频统计
word_counts_top10 = word_counts.most_common(10) # 获取前10最高频的词
print (word_counts_top10) # 输出检查

# 词频展示 
mask = np.array(Image.open('testImg.jpg')) # 定义词频背景
wc = wordcloud.WordCloud(
    font_path='C:/Windows/Fonts/msyh.ttf', # 设置字体格式
    mask=mask, # 设置背景图
    max_words=200, # 最多显示词数
    max_font_size=100, # 字体最大值
    background_color='white'# 设置背景颜色,默认为黑色black
)

fig = plt.figure(figsize=(10, 8)) # 设置显示窗口大小
wc.generate_from_frequencies(word_counts) # 从字典生成词云
image_colors = wordcloud.ImageColorGenerator(mask) # 从背景图建立颜色方案
wc.recolor(color_func=image_colors) # 将词云颜色设置为背景图方案
mpl.rcParams['font.sans-serif'] = ['SimHei']
plt.suptitle('词频分析') #这里设置中文可能会乱码,需要导包
plt.imshow(wc) # 显示词云
plt.axis('off') # 关闭坐标轴
plt.show() # 显示图像
wc.to_file('result.jpg') # 无白边保存图片
fig.savefig('result01.jpg') # 有白边保存

If you want to display and close regularly, you need to add attributes to plt

plt.ion()  # 打开交互模式
plt.show() # 显示图像
plt.pause(15)  # 该句显示图片15秒
plt.ioff()  # 显示完后一定要配合使用plt.ioff()关闭交互模式,否则可能出奇怪的问题
plt.clf()  # 清空图片
plt.close()  # 清空窗口

The expected results can be achieved by executing the above procedures.

wordcloud parameters
font_path : string  #字体路径,需要展现什么字体就把该字体路径+后缀名写上,如:font_path = '黑体.ttf'

width : int (default=400) #输出的画布宽度,默认为400像素

height : int (default=200) #输出的画布高度,默认为200像素

prefer_horizontal : float (default=0.90) #词语水平方向排版出现的频率,默认0.9 (所以词语垂直方向排版出现频率为 0.1 )

mask : nd-array or None (default=None) #如果参数为空,则使用二维遮罩绘制词云。如果 mask 非空,设置的宽高值将被忽略,遮罩形状被 mask 取代。除全白(#FFFFFF)的部分将不会绘制,其余部分会用于绘制词云。如:bg_pic = imread('读取一张图片.png'),背景图片的画布一定要设置为白色(#FFFFFF),然后显示的形状为不是白色的其他颜色。可以用ps工具将自己要显示的形状复制到一个纯白色的画布上再保存,就ok了。

scale : float (default=1) #按照比例进行放大画布,如设置为1.5,则长和宽都是原来画布的1.5倍

min_font_size : int (default=4) #显示的最小的字体大小

font_step : int (default=1) #字体步长,如果步长大于1,会加快运算但是可能导致结果出现较大的误差

max_words : number (default=200) #要显示的词的最大个数

stopwords : set of strings or None #设置需要屏蔽的词,如果为空,则使用内置的STOPWORDS

background_color : color value (default=”black”) #背景颜色,如background_color='white',背景颜色为白色

max_font_size : int or None (default=None) #显示的最大的字体大小

mode : string (default=”RGB”) #当参数为“RGBA”并且background_color不为空时,背景为透明

relative_scaling : float (default=.5) #词频和字体大小的关联性

color_func : callable, default=None #生成新颜色的函数,如果为空,则使用 self.color_func

regexp : string or None (optional) #使用正则表达式分隔输入的文本

collocations : bool, default=True #是否包括两个词的搭配

colormap : string or matplotlib colormap, default=”viridis” #给每个单词随机分配颜色,若指定color_func,则忽略该方法

random_state : int or None  #为每个单词返回一个PIL颜色


fit_words(frequencies)  #根据词频生成词云
generate(text)  #根据文本生成词云
generate_from_frequencies(frequencies[, ...])   #根据词频生成词云
generate_from_text(text)    #根据文本生成词云
process_text(text)  #将长文本分词并去除屏蔽词(此处指英语,中文分词还是需要自己用别的库先行实现,使用上面的 fit_words(frequencies) )
recolor([random_state, color_func, colormap])   #对现有输出重新着色。重新上色会比重新生成整个词云快很多
to_array()  #转化为 numpy array
to_file(filename)   #输出到文件

Guess you like

Origin blog.csdn.net/Lin_Hv/article/details/107173886