#
sys.setdefaultencoding('utf-8')
from
pylab
import
mpl
mpl.rcParams[
'
font.sans-serif
'
] = [
'
FangSong
'
]
#
指定默认字体
mpl.rcParams[
'
axes.unicode_minus
'
] = False
#
解决保存图像是负号'-'显示为方块的问题
plt.rcParams[
'
font.sans-serif
'
] = [
'
SimHei
'
]
stopword
=[u
'
。
'
,u
'
,
'
,u
'
,
'
,u
'
(
'
,u
'
)
'
,u
'
"
'
,u
'
:
'
,u
'
;
'
,u
'
、
'
,u
'
,
'
,u
'
,
'
,u
'
”
'
,u
'
“
'
,u
'
;
'
,u
'
:
'
,u
'
的
'
,u
'
有
'
,u
'
也
'
]
word
=
[]
counter
=
{}
with codecs.open(
'
data.txt
'
) as fr:
for
line
in
fr:
line
=
line.strip()
#
print type(line)
if
len(line) ==
0:
continue
line
= jieba.cut(line, cut_all =
False)
for
w
in
line:
#
.decode('utf-8'):
if
( w
in
stopword)
or
len(w)==1:
continue
if
not
w
in
word :
word.append(w)
if
not
w
in
counter:
counter[w]
=
0
else
:
counter[w]
+= 1
counter_list
= sorted(counter.items(), key=
lambda
x: x[1], reverse=
True)
print
(counter_list[:50
])
#
for i,j in counter_list[:50]:print i
label = list(map(
lambda
x: x[0], counter_list[:10
]))
value
= list(map(
lambda
y: y[1], counter_list[:10
]))
plt.bar(range(len(value)), value, tick_label
=
label)
plt.show()
注意:
matplotlib
展示中文需要进行相应设置
2、利用jieba分词,利用collections统计词频,利用wordcloud生成词云,并定义了 词频背景,最后通过
matplotlib
展示,同样需要设置字体
# coding: utf-8
import sys
reload(sys)
sys.setdefaultencoding('utf8')
# 导入扩展库
import re # 正则表达式库
import collections # 词频统计库
import numpy as np # numpy数据处理库
import jieba # 结巴分词
import wordcloud # 词云展示库
from PIL import Image # 图像处理库
import matplotlib.pyplot as plt # 图像展示库
# 读取文件
fn = open('data.txt') # 打开文件
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'需要'] # 自定义去除词库
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) # 输出检查
# 词频展示
img = Image.open('2018.png') #打开图片
img_array = np.array(img) #将图片装换为数组
#mask = np.array(Image.open('wordcloud.jpg')) # 定义词频背景
wc = wordcloud.WordCloud(
font_path='C:/Windows/Fonts/simhei.ttf', # 设置字体格式
#font_path='/usr/share/fonts/truetype/arphic/ukai.ttc', # 设置字体格式
background_color='white',
mask=img_array,
width=1000,
height=800,
# max_words=200, # 最多显示词数
# max_font_size=100 # 字体最大值
wc.generate_from_frequencies(word_counts) # 从字典生成词云
image_colors = wordcloud.ImageColorGenerator(img_array) # 从背景图建立颜色方案
wc.recolor(color_func=image_colors) # 将词云颜色设置为背景图方案
plt.imshow(wc) # 显示词云
plt.axis('off') # 关闭坐标轴
plt.show() # 显示图像