Python词云图绘制—看博客大佬们的写作热点

《Python可视化展现》中,我们使用了Matplotlib可视化了一些博客大佬们的博客发表年份与数量的关系,接下来我们再看下这些博客文章的热点都有哪些。
我们仅对文章的标题进行分词处理,然后统计分词结果,并绘制出博客文章词云,我们使用了jiebathulac进行中文分词,结果总体差不多,但thulac速度更显得慢。

重新定义walk_tree

def walk_tree_j(html, num):
    for li in html.find_all("li"):
        num = num + 1
        print("%s %s %s%s" % (num, li.h3.a.string, CSDN_BLOG_URL, li.h3.a["href"]))
        k_list = jieba.cut(li.h3.a.string)
        # k_list = thulac.thulac().cut(li.h3.a.string)
        for keyword in k_list:
            # for thulac
            # keyword = str.strip(keyword[0])
            # for jieba
            keyword = str.strip(keyword)
            if len(keyword) < 2:
                pass
            elif keyword_dict.get(keyword, 0) == 0:
                keyword_dict[keyword] = 1
            else:
                keyword_dict[keyword] = keyword_dict[keyword] + 1

        for d in li.find_all("div"):
            if "class" in d.attrs and str.strip(d["class"][0]) == "unit-control":
                print(d.div.find_all("div")[0].string + ",发表时间:" + d.div.find_all("div")[1].string + ",阅读量:" +
                      d.div.find_all("div")[2].span.string + ",评论数:" + d.div.find_all("div")[3].span.string)
                t_value = d.div.find_all("div")[1].string
                year = int(str.strip(t_value)[0:4])
                if article_dict.get(year, 0) == 0:
                    article_dict[year] = 1
                else:
                    article_dict[year] = article_dict[year] + 1

    print(keyword_dict)
    return num

对文章标题进行分词处理,注意,为了简化处理,我们仅去掉单个字符的单词:

k_list = jieba.cut(li.h3.a.string)
# k_list = thulac.thulac().cut(li.h3.a.string)
for keyword in k_list:
    # for thulac
    # keyword = str.strip(keyword[0])
    # for jieba
    keyword = str.strip(keyword)
    if len(keyword) < 2:
        pass
    elif keyword_dict.get(keyword, 0) == 0:
        keyword_dict[keyword] = 1
    else:
        keyword_dict[keyword] = keyword_dict[keyword] + 1

获取到分词结果之后,我们使用wordcloud进行词云绘制

def generate_dict(dic):
    fullTermsDict = multidict.MultiDict()
    for key, value in dic.items():
        fullTermsDict.add(key, value)
    return fullTermsDict


image_path = '1.jpg'
d = path.dirname(__file__)
image = imread(path.join(d, image_path))

wc = WordCloud(background_color="white", max_words=1000, font_path="C:/Windows/Fonts/simkai.ttf", mask=image)
# generate word cloud
fullTermsDict = multidict.MultiDict()
wc.generate_from_frequencies(generate_dict(keyword_dict))
# show
plt.imshow(wc, interpolation="bilinear")
plt.axis("off")
plt.show()

结果查看:

比如,对于:http://blog.csdn.net/phphot

这里写图片描述

比如,对于:http://blog.csdn.net/littletigerat

这里写图片描述

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 猿与汪的秘密 设计师:上身试试 返回首页