Tooling Tuesday: Search Wikipedia with Python!
Ever needed some Wikipedia data in your Python code?
Wikipedia, we all use it! it has replaced Encarta and paper encyclopedias and it is edited by the general public.
But what if I wanted to use it in Python?
So what is it?
A Python library to query Wikipedia in a Pythonic manner which was Created by Jonathan Goldsmith
So how do I install it?
Using pip3
Linux / Mac
sudo pip3 install wikipedia
Windows
pip3 install wikipedia
So how do I use it?
To answer this lets make a little app.
The goal of the app is to
- Suggest a random page from Wikipedia
- Show a summary of the page
- Show the URL of the page
import wikipedia
Import the Wikipedia library.
suggestion = wikipedia.random(pages=1)
Suggest a random page and save that suggestion to a variable.
print("From Wikipedia I found..."+suggestion+"\n")
Print the suggestion to the Python shell, also with a \n
to create a new blank line after printing the suggestion.
print(wikipedia.summary(suggestion)+"\n")
A quick summary of the suggested page.
print(wikipedia.page(suggestion).url)
Print the URL to the Wikipedia article.
Les you said "search" Wikipedia!
Ok, chill!
To search Wikpedia I wrote a few lines of Python.
import wikipedia
query = str(input("What would you like to search for?: "))
found = wikipedia.search(query)
print(found)
I then searched for Raspberry Pi
and it returned a list of data.
['Raspberry Pi', 'Raspberry Pi Foundation', 'Pi-hole', 'Banana Pi', 'Raspbian', 'Carrie Anne Philbin', 'Steam Link', 'Comp
arison of single-board computers', 'DWSIM', 'VideoCore']
import wikipedia
query = str(input("What would you like to search for?: "))
found = wikipedia.search(query)
print("From Wikipedia I found..."+query+"\n")
print(wikipedia.summary(query)+"\n")
print(wikipedia.page(query).url)
Then I reused a little code from the random search project to give me the summary and URL for any page that I search for...so I searched for Greggs...
So where can I find out more
Head over to the Github page and learn more about this fun library.