python词频统计(re和jieba模块的使用),获取词频TOP50的词组

参考

https://www.jianshu.com/p/28718ba04bc9?from=groupmessage
https://blog.csdn.net/qq_32392597/article/details/96147620

爬虫内容

在这里插入图片描述
对应于
在这里插入图片描述

代码

# -*- coding: utf-8 -*-
# import requests
import re
from bs4 import BeautifulSoup
from  urllib.request import urlopen
import collections # 词频统计库
import jieba # 解霸分词

# 获取网页内容
soup = BeautifulSoup(urlopen('http://www.gov.cn/zhengce/2020-02/05/content_5474884.htm'),'lxml')

for data in soup.select('.pages_content'):
    # 不转换成str会报错:TypeError: expected string or bytes-like object
    data = str(data)

    # 文本获取
    pattern = re.compile(r'<p style=\"text-indent.*?12pt;\">(.*?)</p>',re.S)
    content=re.findall(pattern,data)
    str = ''.join(str(i) for i in content)

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

    # 文本分词
    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'需要'] # 自定义去除词库

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

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

输出结果

在这里插入图片描述

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值