首页 > 解决方案 > 在 python 中使用维基百科模块

问题描述

我在我的 python 代码中使用维基百科模块。我希望用户输入从维基百科中搜索并从其摘要中获取 2 行。由于可能有很多同名的主题,所以我这样使用。

import wikipedia
value=input("Enter what u want to search")
m=wikipedia.search(value,3)
print(wikipedia.summary(m[0],sentences=2))

在执行此操作时,它显示了一些 3 页的异常。这有什么问题?编辑:正如@Ruperto 所建议的,我改变了这样的代码。

import wikipedia
import random
value=input("Enter the words: ")
try:
    p=wikipedia.page(value)
    print(p)
except wikipedia.exceptions.DisambiguationError as e:
    s=random.choice(e.options)
    p=wikipedia.summary(s,sentences=2)
    print(p)

现在我得到的错误是,

Traceback (most recent call last):   File "C:\Users\vdhan\AppData\Local\Programs\Python\Python37-32\lib\site-packages\urllib3\connection.py", line 160, in _new_conn
    (self._dns_host, self.port), self.timeout, **extra_kw   File "C:\Users\vdhan\AppData\Local\Programs\Python\Python37-32\lib\site-packages\urllib3\util\connection.py", line 84, in create_connection
    raise err   File "C:\Users\vdhan\AppData\Local\Programs\Python\Python37-32\lib\site-packages\urllib3\util\connection.py", line 74, in create_connection
    sock.connect(sa) TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

During handling of the above exception, another exception occurred:

Traceback (most recent call last):   File "C:\Users\vdhan\AppData\Local\Programs\Python\Python37-32\lib\site-packages\urllib3\connectionpool.py", line 677, in urlopen
    chunked=chunked, urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPConnection object at 0x03AEEAF0>: Failed to establish a new connection: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

现在要做什么?

标签: pythonwikipedia-api

解决方案


正如您的错误所说,这可能是由于没有/糟糕的互联网连接,

A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

您可以更改/检查您的互联网连接,然后重试。两者都不是,这是您的 python 环境的问题。我的实现是,

import warnings
warnings.filterwarnings("ignore")

import wikipedia
import random


value=input("Enter the words: ")
try:
    m=wikipedia.search(value,3)
    print(wikipedia.summary(m[0],sentences=2))
    # print(p)
except wikipedia.exceptions.DisambiguationError as e:
    s=random.choice(e.options)
    p=wikipedia.summary(s,sentences=2)
    print(p)

输出:

Enter the words: programming
Program management or programme management is the process of managing several related projects, often with the intention of improving an organization's performance. In practice and in its aims, program management is often closely related to systems engineering, industrial engineering, change management, and business transformation.

它在 google colab 中运行良好,您可以在此处找到我的实现 colab 文件。


推荐阅读