Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
812 views
in Technique[技术] by (71.8m points)

python - Wikipedia disambiguation error

I have recently been using the wikipedia module to determine a random wikipedia page.

I have been doing this with a very large list of words, and the random.choice() module as so:

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)

The system appears to most often work, but will occasionally choke out the error:

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  

Is there anyway by which I can bypass this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could catch the DisambiguationError and chose one of these pages randomly.

try:
    p = wikipedia.page(string)
except wikipedia.DisambiguationError as e:
    s = random.choice(e.options)
    p = wikipedia.page(s)

see here: http://wikipedia.readthedocs.io/en/latest/quickstart.html


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...