今天教大家使用pyecharm画饼图和直方图。
首先导入所需要的库,分别是 WordCloud、jieba、options,代码如下:
from pyecharts.charts import WordCloud
from pyecharts import options as opts
import jieba # 分词库
词云
首先定义excludes,来表示需要删除的词(可以根据输出结果自行选择),再打开所需要分词的txt文件,使用jieba.lcut()对其进行分词,定义字典,将长度大于1的词放入字典里,再删除不需要的词云,将前100的词云使用词云库进行可视化展示。
excludes = {'公开招标', '项目', '招标人', '招标', '代理', '目的', '委托', '该项', '条件', '具备', '资金', '有限公司', '单位',
'业主', '现对', '批准', '福建省', '建设项目', '施工', '进行', '福建',
}
txt = open("D:\pycharm代码\网络爬虫\招标公告\招标条件.txt", "r", encoding='utf-8').read()
words = jieba.lcut(txt)
counts = {}
for word in words:
if len(word) == 1:
continue
else:
rword = word
counts[rword] = counts.get(rword, 0) + 1
for word in excludes:#删除不需要的词云
del (counts[word])
items = list(counts.items())#将其类型转换为列表
items.sort(key=lambda x: x[1], reverse=True)#对其进行排序
hist = items[:100] # 取前100的词云
#勾画词云图
c = (
WordCloud()
.add(
# 系列名称,用于 tooltip 的显示,legend 的图例筛选。
series_name="招标条件",
# 系列数据项,[(word1, count1), (word2, count2)]
data_pair=hist,
#背景图片
mask_image="D:\pycharm代码\网络爬虫\蓝宝.jpg",
# 单词字体大小范围
word_size_range=[6, 66])
# 全局配置项
.set_global_opts(
# 标题设置
title_opts=opts.TitleOpts(
title="招标条件", title_textstyle_opts=opts.TextStyleOpts(font_size=23)
),
# 提示框设置
tooltip_opts=opts.TooltipOpts(is_show=True),
)
.render("basic_wordcloud.html")
)
运行结果:(如果是pycharm运行的使用chrome,没有显示结果,可以点刷新试试)
全部代码如下:
from pyecharts.charts import WordCloud
from pyecharts import options as opts
import jieba # 分词库
excludes = {'公开招标', '项目', '招标人', '招标', '代理', '目的', '委托', '该项', '条件', '具备', '资金', '有限公司', '单位',
'业主', '现对', '批准', '福建省', '建设项目', '施工', '进行', '福建',
}
txt = open("D:\pycharm代码\网络爬虫\招标公告\招标条件.txt", "r", encoding='utf-8').read()
words = jieba.lcut(txt)
counts = {}
for word in words:
if len(word) == 1:
continue
else:
rword = word
counts[rword] = counts.get(rword, 0) + 1
for word in excludes:
del (counts[word])
items = list(counts.items())
items.sort(key=lambda x: x[1], reverse=True)
txt1 = open("D:\pycharm代码\网络爬虫\招标公告\词频.txt", mode="w")
hist = items[:100] # 取前20的词云
print(hist)
for i in range(100):
word, count = items[i]
txt1.write("{}\t{}\n".format(word, count)) # 将前20个写入文件中
txt1.close()
c = (
WordCloud()
.add(
# 系列名称,用于 tooltip 的显示,legend 的图例筛选。
series_name="招标条件",
# 系列数据项,[(word1, count1), (word2, count2)]
data_pair=hist,
#背景图片
mask_image="D:\pycharm代码\网络爬虫\蓝宝.jpg",
# 单词字体大小范围
word_size_range=[6, 66])
# 全局配置项
.set_global_opts(
# 标题设置
title_opts=opts.TitleOpts(
title="招标条件", title_textstyle_opts=opts.TextStyleOpts(font_size=23)
),
# 提示框设置
tooltip_opts=opts.TooltipOpts(is_show=True),
)
.render("basic_wordcloud.html")
)