'''词汇检索百度返回值,并且计算PMI值的类'''
from bs4 import BeautifulSoup
import requests
import re
import pandas as pd
import time
import numpy as np class PMI():
def __init__(self):
self.url = 'https://www.baidu.com/s?wd='
#self.vocab = vocab def getHtml(self, url): # 只输入URL的主体部分,后面的参数用下面的字典附加上
'''注意这里必须加一个user-Agent,不然request发送请求是是以Python名义发送的,百度知道是Python发的就不给你返回需要的内容,伪装一下'''
try:
header = {
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36",
}
r = requests.get(url, headers=header)
r.raise_for_status()
r.encoding = 'utf-8'
return r.text
except:
print('爬取失败') def getNum(self, html): # 返回搜索的数字
soup = BeautifulSoup(html, 'html.parser')
content = soup.find_all('span', {
'class': 'nums_text'}) # 返回内容为 <span class="nums_text">百度为您找到相关结果约100,000,000个</span>
num = re.findall(r'[\d+,*]+', content[0].string)[
0] # 返回我们需要的搜索次数,内容是字符串型的数字.形如'100,000,000',数字内部包含逗号,下一步需要剔除掉逗号
return int(re.sub(r',', '', num)) # 将逗号替换掉,并强制转换为整数 def retrieveNum(self, vocab): # url主体和爬取网页的数量
url = self.url + vocab
html = self.getHtml(url)
num = self.getNum(html)
return num def getPmi(self,vocab):
n_p = 100000000
n_f = self.retrieveNum(vocab)
n_pf = self.retrieveNum(' '.join(['手机', vocab]))
# print(' '.join(['手机',word]))
# print(n_pf)
pmi = np.log10(n_pf / (n_p * n_f))
return pmi def getPmiList(self,words_list):#返回输入词列表的pmi值,以列表形式
pmi_list=[]
for i in words_list:
pmi_list.append(self.getPmi(i))
return pmi_list if __name__ =='__main__':
time_start = time.time()
url = 'https://www.baidu.com/s?wd='
#print(getHtml( url+'爸爸'))
# file=pd.DataFrame(columns=name,data=comm)
# file.to_csv('D:/machinelearning data/crawlerData/huaWei_P20_JD100-110.csv',index=False)
# num = retrieveNum('办法')
# print('搜索次数为:', num)
d=PMI()
a=['快递','傻子','总体','物流', '验机', '物流', '游戏']#['鸡楚', '留香王者', '系列', '性能', '电池', '电', '视频', '游戏','中华民族', '性价比', '王者', '卡', '天', '红米.', '老婆', '电池', '电', '王者', '时间', '游戏', '相机', '感触', '粉色', '妹妹']
pmi=d.getPmiList(a)
print('PMI:',list(pmi))
time_end = time.time()
print('耗时%s秒' % (time_end - time_start))

  

百度词汇检索,计算PMI值的更多相关文章

  1. geotrellis使用(十七)使用缓冲区分析的方式解决单瓦片计算边缘值问题

    Geotrellis系列文章链接地址http://www.cnblogs.com/shoufengwei/p/5619419.html 目录 前言 需求分析 实现方案 总结 一.前言        最 ...

  2. 百度地图API显示多个标注点并添加百度样式检索窗口

    原作者博客地址:http://blog.csdn.net/a497785609/article/details/24009031 在此基础上进行了修改: 1.添加闭包,将i传入内部 2.添加地图和卫星 ...

  3. treetable 前台 累计计算树值 提交后台

    treetable   累计计算树值 效果图 html  代码 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//E ...

  4. ylbtech-Unitity-cs:计算阶乘值

    ylbtech-Unitity-cs:计算阶乘值 1.A,效果图返回顶部   1.B,源代码返回顶部 1.B.1, using System; namespace Functions { public ...

  5. C#计算时间差值

    /// <summary> /// 计算时间差值 /// </summary> /// <param name="DateTime1">< ...

  6. 利用Python计算π的值,并显示进度条

    利用Python计算π的值,并显示进度条  第一步:下载tqdm 第二步;编写代码 from math import * from tqdm import tqdm from time import ...

  7. excel计算时间差值

    excel计算时间差值 2018/10/1 10:59:00 减去 2018/9/21 1:05:13 获取 多少天. 如1.2天.这种. ==

  8. 使用不同的方法计算TF-IDF值

    摘要 这篇文章主要介绍了计算TF-IDF的不同方法实现,主要有三种方法: 用gensim库来计算tfidf值 用sklearn库来计算tfidf值 用python手动实现tfidf的计算 总结 之所以 ...

  9. C#实现像Git那样计算Hash值

    从Git Tip of the Week: Objects一文中得知,Git是这样计算提交内容的Hash值的: Hash算法用的是SHA1 计算前,会在内容前面添加"blob 内容长度\0& ...

随机推荐

  1. linux查看磁盘占用常用的两个命令

    1.查看总容量.已使用.未使用容量:df -hl -h:以kb以上单位显示 -l:仅显示本地文件系统 2.查看当前路径下,每个文件/夹占用空间大小:du -sh *

  2. 安装新操作系统 Windows 路径设置 节省C盘空间

    1.QQ个人文件夹设置到D盘,D:\ProgramData\QQ 2.IE收藏夹设置到D盘,IE缓存设置到D盘 例如我想把收藏夹默认的保存路径改到D:\study下.关闭Internet Explor ...

  3. myeclipse2016-ci破解疑难杂症问题整理

    感谢网上的各位大神,在你们的基础,我又整理了下安装成功的心得,破解不成功时一定注意下红色字体内容,避免被坑,都是教训. 试了网上N种破解工具+方法,Myeclipse 2016装了很多遍(本人官网下载 ...

  4. discuz 标签详解

    Discuz 模板标签说明 Discuz! 的模板采用近似 PHP 表达式的语法,基本都是可识别的HTML,但涉及到变量和动态内容时,基本形式下: <!-{ 代码内容 }-> 逻辑元素包围 ...

  5. JSTL-taglib

    JSTL(JSP Standard Tag Lib) 目录: Core Fmt Function SimpleTagSupport(jsp 自定义标签) Tag File Core <%@ ta ...

  6. 使用 C++11 编写类似 QT 的信号槽——上篇

    了解 QT 的应该知道,QT 有一个信号槽 Singla-Slot 这样的东西.信号槽是 QT 的核心机制,用来替代函数指针,将不相关的对象绑定在一起,实现对象间的通信. 考虑为 Simple2D 添 ...

  7. libcurl 不支持https访问

    项目中使用libcurl 访问https的时候会报错,比如:“Unsupported protocol” 或者:“Protocol https not supported or disabled in ...

  8. 前端开发-2-HTML

    1.开发环境 市面上有很多的HTML编辑器可以选择,常见的Hbuild.Sublime Text.Dreamweare都可以用来开发HTML. 当然PyCharm也支持HTML开发. 2.文件后缀名规 ...

  9. 获取request错误信息

    from: https://stackoverflow.com/questions/19370436/get-errno-from-python-requests-connectionerror 当使 ...

  10. Eclipse出现错误:The selection cannot be launched,and there are no recent launches

    刚装了eclipse,想写个Java程序测试一下能不能用,结果一run就出现错误,Debug也是同样的错误,错误内容为:the selection cannot be launched,and the ...