侯体宗的博客
  • 首页
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

Python爬取十篇新闻统计TF-IDF

Python  /  管理员 发布于 7年前   187

统计十篇新闻TF-IDF

统计TF-IDF词频,每篇文章的 top10 的高频词存储为 json 文件

TF-IDF

TF-IDF(term frequencyCinverse document frequency)是一种用于资讯检索与文本挖掘的常用加权技术。TF-IDF是一种统计方法,用以评估一字词对于一个文件集或一个语料库中的其中一份文件的重要程度。字词的重要性随着它在文件中出现的次数成正比增加,但同时会随着它在语料库中出现的频率成反比下降。TF-IDF加权的各种形式常被搜索引擎应用,作为文件与用户查询之间相关程度的度量或评级。除了TF-IDF以外,互联网上的搜索引擎还会使用基于连结分析的评级方法,以确定文件在搜寻结果中出现的顺序。
假如一篇文件的总词语数是100个,而词语“母牛”出现了3次,那么“母牛”一词在该文件中的词频就是3/100=0.03。一个计算文件频率(DF)的方法是测定有多少份文件出现过“母牛”一词,然后除以文件集里包含的文件总数。所以,如果“母牛”一词在1,000份文件出现过,而文件总数是10,000,000份的话,其逆向文件频率就是log(10,000,000 / 1,000)=4。最后的TF-IDF的分数为0.03 * 4=0.12。 ―― [ 维基百科 ]

博主选择的是chinadaily的十篇新闻.

1.使用http request请求
2.使用Beautiful Soup来抓取文章标题和内容
3.统计TF-IDF
4.保存到json文件中

代码块

@requires_authorization#coding=utf-8import requestsimport bs4import sysimport mathimport jsonreload(sys)sys.setdefaultencoding('utf-8')url_list = ['http://www.chinadaily.com.cn/china/2016-04/20/content_24701635.htm',      'http://www.chinadaily.com.cn/china/2016-04/20/content_24700746.htm',      'http://www.chinadaily.com.cn/china/2016-04/20/content_24681482.htm',      'http://www.chinadaily.com.cn/china/2016-04/19/content_24675530.htm',      'http://www.chinadaily.com.cn/china/2016-04/19/content_24675455.htm',      'http://www.chinadaily.com.cn/china/2016-04/19/content_24674074.htm',      'http://www.chinadaily.com.cn/china/2016-04/19/content_24655536.htm',      'http://www.chinadaily.com.cn/china/2016-04/18/content_24643685.htm',      'http://www.chinadaily.com.cn/china/2016-04/18/content_24636917.htm',      'http://www.chinadaily.com.cn/china/2016-04/15/content_24562198.htm'      ]articles_title = []articles_content = []for pos,url in enumerate(url_list):  r = requests.get(url)  soup1 = bs4.BeautifulSoup(r.text)  soup2 = bs4.BeautifulSoup(str(soup1.find_all(id="Title_e")))  articles_title.append(soup2.h1.string)  mystr = ""  soup3 = bs4.BeautifulSoup(str(soup1.find_all(id="Content")))  for x in soup3.find_all("p"):    mystr = mystr + x.string  str_p = ""  contents = []  for pos,x in enumerate(mystr):    if x == '.' or x == ',':      if pos < (len(mystr) - 1) and mystr[pos+1] >= '0' and mystr[pos+1] <= '9':        str_p = str_p + x      elif str_p == "":        continue      else:        contents.append(str_p)        str_p = ""    elif x == '(' or x == ')' or x == ' ' or x == '"' or x == '[' or x == ']' or x == '-':      if str_p == "":        continue      else:        contents.append(str_p)        str_p = ""    else:      str_p = str_p + x  articles_content.append(contents)Dict_idf = {}DictList = []for content in articles_content:  Dict_tf = {}  for x in content:    if not Dict_tf.has_key(x):      Dict_tf[x] = 1.0      if not Dict_idf.has_key(x):        Dict_idf[x] = 1.0      else:        Dict_idf[x] += 1.0    else:      Dict_tf[x] += 1.0  for k, v in Dict_tf.items():    Dict_tf[k] = v / len(content)  DictList.append(Dict_tf)for k, v in Dict_idf.items():  Dict_idf[k] = math.log(float(len(url_list)) / v)for pos,x in enumerate(DictList):  for k,v in x.items():    DictList[pos][k] = v*Dict_idf[k]  DictList[pos] = sorted(x.iteritems(), key=lambda d: d[1], reverse=True)"""[  [    article_titile:"XXXX"    [      {        word:"hello"        value:3.5      }      {        word:"hello"        value:3.5      }      {        word:"hello"        value:3.5      }      ...    ]  ]]"""data = []for pos in range(10):  data2=[]  data2.append("article_titile:")  data2.append(articles_title[pos])  data2.append([{"word": k,"value":round(v,4)} for k,v in DictList[pos][:10]])  data.append(data2)# Writing JSON datawith open('data.json', 'w') as f:  json.dump(data, f)

使用json.cn查看数据:

github地址:https://github.com/mqsee/learngit

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


  • 上一条:
    Python如何生成树形图案
    下一条:
    Python制作词云的方法
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 在windows10中升级go版本至1.24后LiteIDE的Ctrl+左击无法跳转问题解决方案(0个评论)
    • 智能合约Solidity学习CryptoZombie第四课:僵尸作战系统(0个评论)
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(95个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客