Python的Wikipedia API入门

您所在的位置:网站首页 维基百科查不到 Python的Wikipedia API入门

Python的Wikipedia API入门

2024-06-02 17:33| 来源: 网络整理| 查看: 265

介绍

在本文中,我们将使用Wikipedia API从Wikipedia检索数据。 由于越来越多地使用数据分析和机器学习工具,数据抓取迅速增长。 互联网是最大的信息来源,因此了解如何从各种来源获取数据非常重要。 由于Wikipedia是Internet上最大和最受欢迎的信息来源之一,因此这是一个自然的起点。

在本文中,我们将看到如何使用Python的Wikipedia API从Wikipedia网站获取各种信息。

安装

为了从Wikipedia提取数据,我们必须首先安装Python Wikipedia库,该库包装了正式的Wikipedia API。 这可以通过在命令提示符或终端中输入以下命令来完成:

1$ pip install wikipedia

安装完成后,我们可以使用Python中的Wikipedia API从Wikipedia中提取信息。 为了在Python中调用Wikipedia模块的方法,我们需要使用以下命令将其导入。

1import wikipedia 搜索标题和建议

search()方法在Wikipedia中搜索作为其参数提供的查询。 结果,此方法返回包含该查询的所有文章标题的列表。 例如:

12import wikipedia print(wikipedia.search("Bill"))

输出:

1['Bill', 'The Bill', 'Bill Nye', 'Bill Gates', 'Bills, Bills, Bills', 'Heartbeat bill', 'Bill Clinton', 'Buffalo Bill', 'Bill & Ted', 'Kill Bill: Volume 1']

如您在输出中看到的,将显示搜索到的标题以及相关的搜索建议。 您可以通过传递results参数的值来配置返回的搜索标题的数量,如下所示:

12import wikipedia print(wikipedia.search("Bill", results=2))

输出:

1['Bill', 'The Bill']

上面的代码仅打印查询的2个搜索结果,因为这是我们要求返回的数量。

假设我们需要获取错误输入或有错字的搜索标题" Bill Cliton"的Wikipedia搜索建议。 suggest()方法返回与作为参数输入的搜索查询相关的建议,如果找不到建议,它将返回" None"。

让我们在这里尝试一下:

12import wikipedia print(wikipedia.suggest("Bill cliton"))

输出:

1bill clinton

您会看到我们输入了错误的" Bill clinton",并返回了正确的建议" bill clinton"。

提取维基百科文章摘要

我们可以使用summary()方法提取Wikipedia文章的摘要。 需要为其提取摘要的文章作为参数传递给此方法。

让我们提取" Ubuntu"的摘要:

1print(wikipedia.summary("Ubuntu"))

输出:

1Ubuntu ( (listen)) is a free and open-source Linux distribution based on Debian. Ubuntu is officially released in three editions: Desktop, Server, and Core (for the internet of things devices and robots). Ubuntu is a popular operating system for cloud computing, with support for OpenStack.Ubuntu is released every six months, with long-term support (LTS) releases every two years. The latest release is 19.04 ("Disco Dingo"), and the most recent long-term support release is 18.04 LTS ("Bionic Beaver"), which is supported until 2028. Ubuntu is developed by Canonical and the community under a meritocratic governance model. Canonical provides security updates and support for each Ubuntu release, starting from the release date and until the release reaches its designated end-of-life (EOL) date. Canonical generates revenue through the sale of premium services related to Ubuntu. Ubuntu is named after the African philosophy of Ubuntu, which Canonical translates as"humanity to others" or"I am what I am because of who we all are".

整个摘要将打印在输出中。 通过配置方法的sentences参数,我们可以自定义要显示的摘要文本中的句子数。

1print(wikipedia.summary("Ubuntu", sentences=2))

输出:

1Ubuntu ( (listen)) is a free and open-source Linux distribution based on Debian. Ubuntu is officially released in three editions: Desktop, Server, and Core (for the internet of things devices and robots).

如您所见,Ubuntu的文本摘要仅打印了两个句子。

但是,请记住,如果页面不存在或页面是明确的,则wikipedia.summary将引发"歧义消除错误"。 让我们来看一个例子。

1print(wikipedia.summary("key"))

上面的代码抛出DisambiguationError,因为有许多文章与" key"匹配。

输出:

1234567891011121314151617Traceback (most recent call last):   File"", line 1, in   File"/Library/Python/2.7/site-packages/wikipedia/util.py", line 28, in __call__     ret = self._cache[key] = self.fn(*args, **kwargs)   File"/Library/Python/2.7/site-packages/wikipedia/wikipedia.py", line 231, in summary     page_info = page(title, auto_suggest=auto_suggest, redirect=redirect)   File"/Library/Python/2.7/site-packages/wikipedia/wikipedia.py", line 276, in page     return WikipediaPage(title, redirect=redirect, preload=preload)   File"/Library/Python/2.7/site-packages/wikipedia/wikipedia.py", line 299, in __init__     self.__load(redirect=redirect, preload=preload)   File"/Library/Python/2.7/site-packages/wikipedia/wikipedia.py", line 393, in __load     raise DisambiguationError(getattr(self, 'title', page['title']), may_refer_to) wikipedia.exceptions.DisambiguationError:"Key" may refer to: Key (cryptography) Key (lock) Key (map) ...

例如,如果您想要摘要关于"加密密钥",则必须输入以下内容:

1print(wikipedia.summary("Key (cryptography)"))

通过更具体的查询,我们现在在输出中获得正确的摘要。

检索完整的维基百科页面数据

为了获取Wikipedia页面的内容,类别,坐标,图像,链接和其他元数据,我们必须首先获取Wikipedia页面对象或页面的页面ID。 为此,将page()方法与页面标题一起用作该方法的参数。

看下面的例子:

1wikipedia.page("Ubuntu")

此方法调用将返回一个WikipediaPage对象,我们将在接下来的几节中对其进行详细介绍。

提取页面的元数据

要获得Wikipedia页面的完整纯文本内容(不包括图像,表格等),我们可以使用page对象的content属性。

1print(wikipedia.page("Python").content)

输出:

12Python is an interpreted, high-level, general-purpose programming language. Created by Guido van Rossum and first released in 1991, Python's design philosophy emphasizes code readability with its notable use of significant whitespace. Its language constructs and object-oriented approach aims to help programmers write clear, logical code for small and large-scale projects.Python is dynamically typed and garbage-collected. It supports multiple programming paradigms, including procedural, object-oriented, and  functional programming. Python is often described as a"batteries included" language due to its comprehensive standard library.Python was conceived in the late 1980s as a successor to the ABC language. Python 2.0, released 2000, introduced features like list comprehensions and a garbage collection system capable of collecting reference cycles. ...

同样,我们可以使用url属性获取页面的URL:

1print(wikipedia.page("Python").url)

输出:

1https://en.wikipedia.org/wiki/Python_(programming_language)

通过使用WikipediaPage对象的references属性,我们可以在Wikipedia页面上获取外部链接的URL。

1print(wikipedia.page("Python").references)

输出:

1[u'http://www.computerworld.com.au/index.php/id;66665771', u'http://neopythonic.blogspot.be/2009/04/tail-recursion-elimination.html', u'http://www.amk.ca/python/writing/gvr-interview', u'http://cdsweb.cern.ch/journal/CERNBulletin/2006/31/News%20Articles/974627?ln=en', u'http://www.2ality.com/2013/02/javascript-influences.html', ...]

WikipediaPage对象的title属性可用于提取页面标题。

1print(wikipedia.page("Python").title)

输出:

1Python (programming language)

类似地,categories属性可用于获取Wikipedia页面的类别列表:

1print(wikipedia.page("Python").categories)

输出量

1['All articles containing potentially dated statements', 'Articles containing potentially dated statements from August 2016', 'Articles containing potentially dated statements from December 2018', 'Articles containing potentially dated statements from March 2018', 'Articles with Curlie links', 'Articles with short description', 'Class-based programming languages', 'Computational notebook', 'Computer science in the Netherlands', 'Cross-platform free software', 'Cross-platform software', 'Dutch inventions', 'Dynamically typed programming languages', 'Educational programming languages', 'Good articles', 'High-level programming languages', 'Information technology in the Netherlands', 'Object-oriented programming languages', 'Programming languages', 'Programming languages created in 1991', 'Python (programming language)', 'Scripting languages', 'Text-oriented programming languages', 'Use dmy dates from August 2015', 'Wikipedia articles with BNF identifiers', 'Wikipedia articles with GND identifiers', 'Wikipedia articles with LCCN identifiers', 'Wikipedia articles with SUDOC identifiers']

WikipediaPage对象的links元素可用于获取页面中存在链接的页面标题列表。

1print(wikipedia.page("Ubuntu").links)

输出量

1[u'/e/ (operating system)', u'32-bit', u'4MLinux', u'ALT Linux', u'AMD64', u'AOL', u'APT (Debian)', u'ARM64', u'ARM architecture', u'ARM v7', ...] 根据坐标查找页面

geosearch()方法用于使用作为方法的浮点数或十进制数提供的纬度和经度参数来进行Wikipedia地理搜索。

1print(wikipedia.geosearch(37.787, -122.4))

输出:

1['140 New Montgomery', 'New Montgomery Street', 'Cartoon Art Museum', 'San Francisco Bay Area Planning and Urban Research Association', 'Academy of Art University', 'The Montgomery (San Francisco)', 'California Historical Society', 'Palace Hotel Residential Tower', 'St. Regis Museum Tower', 'Museum of the African Diaspora']

如您所见,以上方法根据提供的坐标返回文章。

同样,我们可以设置page()的坐标属性,并获取与地理位置有关的文章。 例如:

1print(wikipedia.page(37.787, -122.4))

输出:

1['140 New Montgomery', 'New Montgomery Street', 'Cartoon Art Museum', 'San Francisco Bay Area Planning and Urban Research Association', 'Academy of Art University', 'The Montgomery (San Francisco)', 'California Historical Society', 'Palace Hotel Residential Tower', 'St. Regis Museum Tower', 'Museum of the African Diaspora'] 语言设定

您可以将Wikipedia页面的语言自定义为您的母语,前提是该页面以您的母语存在。 为此,可以使用set_lang()方法。 每种语言都有一个标准的前缀代码,该代码作为参数传递给该方法。 例如,以德语获取" Ubuntu" Wiki页面的摘要文本的前两个句子。

12wikipedia.set_lang("de")   print(wikipedia.summary("ubuntu", sentences=2))

输出量

1Ubuntu (auch Ubuntu Linux) ist eine Linux-Distribution, die auf Debian basiert. Der Name Ubuntu bedeutet auf Zulu etwa ?Menschlichkeit" und bezeichnet eine afrikanische Philosophie.

您可以检查当前支持的ISO语言列表及其前缀,如下所示:

1print(wikipedia.languages()) 检索维基百科页面中的图像

WikipediaPage对象的images列表可用于从Wikipedia页面获取图像。 例如,以下脚本从Wikipedia的Ubuntu页面返回第一个图像:

1print(wikipedia.page("ubuntu").images[0])

输出量

1https://upload.wikimedia.org/wikipedia/commons/1/1d/Bildschirmfoto_zu_ubuntu_704.png

上面的代码返回Wikipedia页面中索引0处存在的图像的URL。

要查看图像,您可以将以上URL复制并粘贴到浏览器中。

检索完整的HTML页面内容

要获取HTML格式的完整Wikipedia页面,可以使用以下脚本:

1print(wikipedia.page("Ubuntu").html())

输出量

123For the African philosophy, see Ubuntu philosophy. For other uses, see Ubuntu (disambiguation). Linux distribution based on Debian ...

从输出中可以看到,将以HTML格式显示整个页面。 如果页面很大,则加载时间可能会更长一些,因此请记住,当对服务器的请求超时时,它可能会引发HTMLTimeoutError。

结论

在本教程中,我们瞥见了使用Wikipedia API从网络提取数据的过程。 我们看到了如何获取各种信息,例如页面的标题,类别,链接,图像,以及如何根据地理位置检索文章。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3