通过Python获取维基百科中概念词条的维基信息

维基百科作为全球网络上最大且最受欢迎的参考工具书目前已被许多自然语言处理方面的研究人员所青睐,并将其视为优质的语言资料来源。大多数情况下,我们获取维基百科信息是通过其提供的数据库(http://dumps.wikimedia.org)来实现,但是其数据量巨大让我们难以转存至自己的本机数据库当中(英文的基本10G以上,电脑没有16G内存基本上搞不定),因此如何快速获取其维基数据一直是个难题。
通过在实验室研究基于维基百科的概念先决条件关系,本人开发出一套合理的程序,访问维基百科的API(https://www.mediawiki.org/wiki/API:Main_page)来获取维基信息,由于维基百科的基本信息量非常大,所以不可能面面俱到,但是本程序涉及到维基百科当中的大部分概念特征例如(引用关系、分类关系等),因此举一反三我们也可以获取到其余的所有信息。另外Python的第三方库也提供了可以访问维基百科的接口,但是实际测试发现其网络速度会受到时间限制,因此使用当中会感觉到很慢或者直接报错,如果有兴趣可以自行前去了解(wikipedia)。
希望本文对NLP感兴趣的研究者和维基百科爱好者有所帮助。

# -*- coding:utf-8 -*-
# Author:Zhou Yangimport requests
import json
import logging
import sys
import os.path
import reagreement = 'https://'
language = 'en'
organization = '.wikipedia.org/w/api.php'API_URL = agreement + language + organizationprogram = os.path.basename(sys.argv[0])
logger = logging.getLogger(program)
logging.basicConfig(format='%(asctime)s: %(levelname)s: %(message)s')def pageid(title = None, np = 0):global API_URLURL = API_URLquery_params = {'action': 'query','prop': 'info','format': 'json','titles': title}if np != 0:query_params['titles'] = 'Category:' + titletry:r = requests.get(URL, params=query_params)r.raise_for_status()html, r.encoding = r.text, 'gb2312'except:html = ""if html == "":return -1else:try:text = json.loads(html, encoding='gb2312')except json.JSONDecodeError:return -1try:for i in text["query"]['pages']:return int(i)except:return -1def summary(title = None):global API_URLURL = API_URLquery_params = {'action': 'query','prop': 'extracts','explaintext': '','exintro': '','format': 'json','titles': title}try:r = requests.get(URL, params=query_params)r.raise_for_status()html, r.encoding = r.text, 'gb2312'except:logger.error('error summary about ' + title)return ""text = json.loads(html, encoding='gb2312')id = list(text["query"]["pages"].keys())[0]try:return text["query"]["pages"][id]["extract"]except:return ""def body(title = None):global API_URLURL = API_URLquery_params = {'action': 'query','prop': 'extracts','exlimit' : 'max','format': 'json','titles': title}try:r = requests.get(URL, params=query_params)r.raise_for_status()html, r.encoding = r.text, 'gb2312'except:logger.error('error body about ' + title)return ""text = json.loads(html, encoding='gb2312')id = list(text["query"]["pages"].keys())[0]try:html_text = text["query"]["pages"][id]["extract"]def stripTagSimple(htmlStr):'''最简单的过滤html <>标签的方法    注意必须是<任意字符>  而不能单纯是<>:param htmlStr:'''#         dr =re.compile(r'<[^>]+>',re.S)dr = re.compile(r'</?\w+[^>]*>', re.S)htmlStr = re.sub(dr, '', htmlStr)return htmlStrhtml_text = stripTagSimple(html_text)html_text = str(html_text).replace("\n", "")return html_textexcept:return ""def links(title = None):global API_URLURL = API_URLquery_params = {'action': 'query','prop': 'links','pllimit': 'max','plnamespace': '0','format': 'json','titles': title}try:r = requests.get(URL, params=query_params)r.raise_for_status()html, r.encoding = r.text, 'gb2312'except:logger.error('error links about ' + title)return list()text = json.loads(html, encoding='gb2312')id = list(text["query"]["pages"].keys())[0]link = list()summ = summary(title)try:for obj in text["query"]['pages'][id]["links"]:if obj['title'] in summ or obj['title'].lower() in summ:link.append(obj['title'])except:return linkreturn linkdef linkss(title = None):global API_URLURL = API_URLquery_params = {'action': 'query','prop': 'links','pllimit': 'max','plnamespace': '0','format': 'json','titles': title}try:r = requests.get(URL, params=query_params)r.raise_for_status()html, r.encoding = r.text, 'gb2312'except:logger.error('error linkss about ' + title)return list()text = json.loads(html, encoding='gb2312')id = list(text["query"]["pages"].keys())[0]link = list()try:for obj in text["query"]['pages'][id]["links"]:link.append(obj['title'])except:return linkreturn linkdef backlinks(title = None):global API_URLURL = API_URLquery_params = {'action': 'query','list': 'backlinks','bllimit': 'max','blnamespace': '0','format': 'json','bltitle': title}try:r = requests.get(URL, params=query_params)r.raise_for_status()html, r.encoding = r.text, 'gb2312'except:logger.error('error backlinks about ' + title)return list()text = json.loads(html, encoding='gb2312')link = list()try:link = [obj['title'] for obj in text["query"]["backlinks"]]except:return linkreturn linkdef categories(title = None):global API_URLURL = API_URLquery_params = {'action': 'query','prop': 'categories','cllimit': 'max','clshow': '!hidden','format': 'json','clcategories': '','titles': title}try:r = requests.get(URL, params=query_params)r.raise_for_status()html, r.encoding = r.text, 'gb2312'except:logger.error('error categories about ' + title)return list()text = json.loads(html, encoding='gb2312')id = list(text["query"]["pages"].keys())[0]category = set()if id != -1:try:category = [obj['title'][9:] for obj in text["query"]['pages'][id]["categories"]]except:return categoryreturn categorydef redirects(title=None):global API_URLURL = API_URLquery_params = {'action': 'query','prop': 'redirects','rdlimit': 'max','format': 'json','titles': title}try:r = requests.get(URL, params=query_params)r.raise_for_status()html, r.encoding = r.text, 'gb2312'except:logger.error('error redirects about ' + title)return list()text = json.loads(html, encoding='gb2312')id = list(text["query"]["pages"].keys())[0]redirect = list()if id != -1:try:redirect = [obj['title'] for obj in text["query"]['pages'][id]["redirects"]]except:return redirectreturn redirectdef subcats(title=None):global API_URLURL = API_URLquery_params = {'action': 'query','list': 'categorymembers','cmtype': 'subcat','cmlimit': 'max','format': 'json','cmtitle': 'Category:' + title}try:r = requests.get(URL, params=query_params)r.raise_for_status()html, r.encoding = r.text, 'gb2312'except:logger.error('error subcats about ' + title)return list()text = json.loads(html, encoding='gb2312')subcat = list()try:subcat = [obj['title'][9:] for obj in text["query"]['categorymembers']]except:return subcatreturn subcatdef supercats(title=None):global API_URLURL = API_URLquery_params = {'action': 'query','prop': 'categories','cllimit': 'max','format': 'json','clshow': '!hidden','titles': 'Category:' + title}try:r = requests.get(URL, params=query_params)r.raise_for_status()html, r.encoding = r.text, 'gb2312'except:logger.error('error supercats about ' + title)return list()text = json.loads(html, encoding='gb2312')id = list(text["query"]["pages"].keys())[0]supercat = list()if id != -1:try:supercat = [obj['title'][9:] for obj in text["query"]['pages'][id]["categories"]]except:return supercatreturn supercatdef contributors(title=None):global API_URLURL = API_URLquery_params = {'action': 'query','prop': 'contributors','pclimit': 'max','format': 'json','titles': title}try:r = requests.get(URL, params=query_params)r.raise_for_status()html, r.encoding = r.text, 'gb2312'except:logger.error('error linkss about ' + title)return list()text = json.loads(html, encoding='gb2312')id = list(text["query"]["pages"].keys())[0]contributors = list()try:for obj in text["query"]['pages'][id]["contributors"]:contributors.append(obj['userid'])except:return contributorsreturn contributorsif __name__ == '__main__':title = "Computer networks"id = pageid(title, np = 4)summ = summary(title)Out = links(title)print(id)print(summ)print(Out)
  • 获取维基概念的ID(“Machine learning”)
233488
  • 获取摘要部分(“Machine learning”)
Machine learning (ML) is the scientific study of algorithms and statistical models that computer systems use to effectively perform a specific task without using explicit instructions, relying on patterns and inference instead. It is seen as a subset of artificial intelligence. Machine learning algorithms build a mathematical model of sample data, known as "training data", in order to make predictions or decisions without being explicitly programmed to perform the task. Machine learning algorithms are used in a wide variety of applications, such as email filtering, and computer vision, where it is infeasible to develop an algorithm of specific instructions for performing the task. Machine learning is closely related to computational statistics, which focuses on making predictions using computers. The study of mathematical optimization delivers methods, theory and application domains to the field of machine learning. Data mining is a field of study within machine learning, and focuses on exploratory data analysis through unsupervised learning. In its application across business problems, machine learning is also referred to as predictive analytics.
  • 获取页面上的超链接概念(“Machine learning”)
['Algorithm', 'Artificial intelligence', 'Computational statistics', 'Computer systems', 'Computer vision', 'Data mining', 'Email filtering', 'Exploratory data analysis', 'Inference', 'Mathematica', 'Mathematical optimization', 'Predictive analytics', 'STATISTICA', 'Statistical model', 'Statistics', 'Supervised learning', 'Training data']

更多功能可以自己尝试去调用,提醒一下的是访问不同语言的话只需要修改代码里面的language参数即可,本文使用的英文维基百科,访问中文只需改为“zh”,但是访问中文需要翻墙,其余的语言类似。

本人第一次写技术博客,有什么不足的地方欢迎各位指正!

通过Python获取维基百科中概念词条的维基信息相关推荐

  1. python百科全书_维基百科中的数据科学:手把手教你用Python读懂全球最大百科全书...

    image 大数据文摘出品 编译:狗小白.李佳.张弛.魏子敏 没人否认,维基百科是现代最令人惊叹的人类发明之一. 几年前谁能想到,匿名贡献者们的义务工作竟创造出前所未有的巨大在线知识库?维基百科不仅是 ...

  2. python遍历文本文件统计字符个数_用python获取txt文件中关键字的数量

    缘起: 开发人员需要tomcat中一个项目在一个月的访问请求量,因其他原因只剩下查找tomcat请求日志的方法获取,刚好最近在学习python,于是就用python摸索了下: 大体思路: 1.把相应t ...

  3. python获取List数组中重复元素的个数(arcpy中统计FeatureClass中各类型地物要素的图斑数)(地理国情监测)

    python获取List数组中重复元素的个数(arcpy中统计FeatureClass中各类型地物要素的图斑数)(地理国情监测) for str_Val in set(shp_JH_list): #循 ...

  4. 使用python获取共享汽车平台Evcard 的车辆位置信息

    通过python获取共享汽车平台Evcard 的车辆位置信息* 我们直接开门见山,但是本文只是提供一个思路,具体还需要大家自行操作(由于是第一次写,有些许的紧张,如有错误的地方,望大家不吝赐教). 因 ...

  5. 通过python获取苹果手机备份文件中的照片,视频等信息采集

    前言: 苹果手机用户通常会将手机备份到电脑上,而备份文件通常不会自动删除.在我们电脑取证,或者***到一台电脑后可以通过python脚本获取到备份文件中的一些隐私信息,比如照片.视频.相关软件中的一些 ...

  6. iphone看python文件_通过python获取苹果手机备份文件中的照片,视频等信息采集

    前言: 苹果手机用户通常会将手机备份到电脑上,而备份文件通常不会自动删除.在我们电脑取证,或者***到一台电脑后可以通过python脚本获取到备份文件中的一些隐私信息,比如照片.视频.相关软件中的一些 ...

  7. 使用Python获取Excel文件中单元格公式的计算结果

    假设有如下Excel文件,其中第二个WorkSheet中数据如下: 其中D列为公式,现在要求输出该列公式计算的数值结果,代码如下: 代码运行结果: ----------相关阅读---------- 1 ...

  8. python获取csv文件中某一列或者某些列

    把三个csv文件中的feature值整合到一个文件中,同时添加相应的label. # -*-coding:utf-8 -*- import csv; label1 = '1' label2 = '2' ...

  9. Python 获取文件夹中的文件列表

    获取文件夹中的文件列表 问题 你想获取文件系统中某个目录下的所有文件列表. 解决方案 使用 os.listdir() 函数来获取某个目录中的文件列表: import os names = os.lis ...

  10. 用Python获取大众点评上长沙口味虾店铺信息,并进行数据分析

    口味虾又叫麻辣小龙虾.在夏天的时候,邀上三五好友,来上几盘口味虾,搭配上啤酒,肥宅的生活就这么快乐的开始了,味道麻辣爽口,一口下去就想吃下一口!在湖南,没有吃上口味虾的夏天都是不完整的. 那么湖南的吃 ...

最新文章

  1. C语言解析命令行函数:getopt系列
  2. 架构师之路 — 部署架构 — 高可用集群 — 主备 HA 系统中的脑裂问题
  3. word 常用快捷键
  4. 一个能极大提高生产率的Chrome新建标签页扩展
  5. 1285B. Just Eat It
  6. 隐马尔可夫模型,最大熵马尔可夫模型和条件随机场的区别与联系
  7. fedora 16 x64 安装gnustep object-c开发环境
  8. excel导入Mysql之间的转换
  9. 电子书下载:[FBI教你破解身体语言].(美)乔·纳瓦罗.(美)马文·卡尔林斯.文字版...
  10. Android学习资料网站搜集
  11. 软件测试简历写成这样,还怕HR不招你?
  12. 如何隐藏电脑下方工具栏个别图标_电脑下方隐藏小图标怎么设置
  13. 给电视盒子换上第三方桌面
  14. Android 获取assets文件夹下面的文件路径
  15. Ubuntu下好用的文档比较工具Meld,代替Notepad++的文档对比功能?
  16. Matlab论文插图绘制模板—柱状图(单组多色)
  17. 进阿里一年中最好的机会
  18. NPOI导出漂亮的Excel报表
  19. 项目2-企业级电商平台的搭建--填坑过程
  20. 越努力,越幸运—2021年终总结

热门文章

  1. Excel如何批量生成条形码
  2. 50.网络安全渗透测试—[穷举篇13]—[wfuzz多线程百万密码测试指定后台破解]
  3. 监管大屏系统_国网信息运维综合监管系统及大屏可视化平台建设介绍
  4. 关于阿里云主机数据丢失问题,是常态还是个例?如何保障数据安全?...
  5. Java集合类和数组之间的相互转换
  6. Windows10出现“ Trusted Installer 提供的权限才能对此文件进行更改”的处理
  7. 2021充电必备:推荐一些免费的电子书网站及TXT阅读器
  8. 数据库概述05(数据库查询及修改操作)
  9. 分享ZKEYS公有云分销系统部署详细教程
  10. 导师对计算机学生论文的评语,导师对论文的学术评语