2014-09-20 73 views
1

我最近一直在使用维基百科模块来确定一个随机的维基百科页面。维基百科消歧错误

我一直在用言语非常大名单这样做,和random.choice()模块像这样:

words=open("words.txt","r") 
words=words.read() 

words=words.split()  

text=random.choice(words) 

string=random.choice(wikipedia.search(text)) 

p = wikipedia.page(string) 

系统似乎最常打交道的,不过偶尔也会憋出来的错误:

Traceback (most recent call last): 
    File "/home/will/google4.py", line 25, in <module> 
    p = wikipedia.page(string) 
    File "/usr/local/lib/python2.7/dist-packages/wikipedia/wikipedia.py", line 276, in page 
    return WikipediaPage(title, redirect=redirect, preload=preload) 
    File "/usr/local/lib/python2.7/dist-packages/wikipedia/wikipedia.py", line 299, in __init__ 
    self.__load(redirect=redirect, preload=preload) 
    File "/usr/local/lib/python2.7/dist-packages/wikipedia/wikipedia.py", line 393, in __load 
    raise DisambiguationError(getattr(self, 'title', page['title']), may_refer_to) 
DisambiguationError: "The Scarf" may refer to: 
The Scarf (film) 
The Scarf (opera) 
Scarf (disambiguation) 
Arthur Stewart King Scarf 

有反正我可以绕过吗?

回答

1

一个显而易见的方式是下载维基百科页面名称的完整列表,并使用它来代替您的单词列表。这对维基百科的搜索引擎来说也是非常友善的,因为你不需要获得一个随机页面(此外,如果你想要一个统一的随机页面,你不能使用搜索引擎)。

一个不太好但可能更简单的解决方法是您只需尝试/除了DisambiguationError并再试一次。

1

更重要的是,在您的处置使用工具:

wikipedia.random(pages=1) 

Get a list of random Wikipedia article titles. 

Note 

Random only gets articles from namespace 0, meaning no Category, User talk, or other meta-Wikipedia pages. 

Keyword arguments: 

    pages - the number of random pages returned (max of 10) 

(从https://wikipedia.readthedocs.io/en/latest/code.html#api