Wikipedia Module in Python

In this tutorial, you will learn about Wikipedia Module in Python. Wikipedia is one of the most used online encyclopediae. Therefore it is useful to know how to fetch data from Wikipedia. Using this module we can get articles, images, preference, and many more from Wikipedia. We will see how to use the Wikipedia module of Python to fetch a variety of information from the Wikipedia website for our needs.

Installation of  Wikipedia Module

For fetching data from Wikipedia, we must first install the Python Wikipedia library, which wraps the official Wikipedia API. Enter the command below in your terminal to install the Python Wikipedia library.

pip install wikipedia

After installing the library,  import the Wikipedia module using the command below.

import wikipedia

Methods

Wikipedia module contains many methods. In this tutorial, we will see some commonly used methods from this module.

Search() and Suggest()

Titles and suggestions for a word can be get by using the search() method and suggest() method.

import wikipedia 
print(wikipedia.search("April"))
print(wikipedia.suggest("Aril")) #There is typo in word "April"

After executing the code, you get results in an above-shown manner. Sometimes output may contain many suggestions for a single word. So use the results keyword for solving this issue.

SYNTAX:Wikipedia.search(title, results)

import wikipedia 
print(wikipedia.search("April",results=5)
OUTPUT:
['April', "April Fools' Day", 'April 1', 'April 4', 'April, april']

Summary()

A total page summary for any title can be obtained using the Summary() method.

import wikipedia  
print(wikipedia.summary("Coronavirus"))  
  

Wikipedia contains big data, Fetching that much big data sometimes make IDE slow and It may also irritate the user. For making big data into small ones with limited sentences, use the sentence keyword.

SYNTAX: Wikipedia.summary(title, sentences)

import wikipedia 
print(wikipedia.summary("Coronavirus",sentences=7))

Page()

Wikipedia pages contain many columns(i.e pictures, text, links, ..etc). Using page() method we can retrieve the following from the page:

  • contents
  • categories
  • coordinates
  • images
  • links
import wikipedia
print(wikipedia.page("Lion").content)
print(wikipedia.page("Lion").url)
print(wikipedia.page("Lion").references)
print(wikipedia.page("Lion").title)
print(wikipedia.page("Lion").categories)
print(wikipedia.page("Lion").links)
print(wikipedia.geosearch(27.777, -182.4))
print(wikipedia.page("Lion").images[0])

Conclusionq

In this tutorial, we have seen a brief description and uses of the Wikipedia module in python.

Further reading:

Reference: Wikipedia API

Leave a Reply

Your email address will not be published. Required fields are marked *