爬取简书网30日热门得到词云 续

前面所使用的jieba分词中,是自行收集一些不重要的词进行过滤的,效率不是很高,并且带有比较大的主观性(算是优点,也算是缺点)。

本次则改为使用中文停用词表来过滤一些词语。代码相对于上一节来说变化的主要是analysis.py 中的analysis函数。

代码大致如下:

import jieba.analyse
def analysis(db_name, collection_name):
    ''' 
    分析数据
    @param db_name mongo数据库名
    @param collection_name 集合名称
    @return 返回collections.Counter
    '''
    client = pymongo.MongoClient('localhost', 27017)
    mydb = client[db_name]
    jianshu = mydb[collection_name]

    #获取所有数据,返回的为一个迭代器
    results = jianshu.find()
    #计数器
    counter = Counter()

    #停用词表
    jieba.analyse.set_stop_words('./chinese_stop_words.txt')

    for result in results:
        text = result['text']
        tags = jieba.analyse.extract_tags(text, withWeight = True)
        #tags = jieba.analyse.extract_tags(text, topK = 100, withWeight = True)

        for item in tags:
            counter[item[0]] += item[1]

    return counter

因为本次目标是对所有的文章进行分词,所以还是需要Counter进行计数,只不过添加了一个停用词表过滤词语。

jieba.analyse.extract_tags()中的topK表示取出前若干个频率最高的词,返回的是list[tuple(词, 频率)],这里因为是对所有的文章进行分析,所以并没有加入参数topK;若加入则会根据topK大小而使得生成的词云也会有所不同。

运行结果大致如下:

 权重最大的是"简书",这个情有可原。抛开这个的话,出现的较多的有"写作"、“文章”、“大学”...

更改后的代码:

https://github.com/sky94520/jianshu_month/tree/jianshu-02

猜你喜欢

转载自blog.csdn.net/bull521/article/details/84890855
今日推荐