How to create Wikipedia bot using python - Source code
As Wikipedia is the largest source of information on the internet so we should have the knowledge to fetch information from it. In python, we have a package/library named Wikipedia(based on Wikipedia API) to get information from Wikipedia. Wikipedia package contains few methods so we use them to get information.
To use the Wikipedia package you need to install it into your system if you have not installed it yet. Paste the following command into terminal and press enter. After that, it will be installed into your system.
To create text-to-speech functionality in our Wikipedia bot we will use another python package named pyttsx3. It’s a python package that can convert any given text into speech. If you want to know further about it you can read an article about it just click here to read.
To use pyttsx3 install it first. Use the following command to install.
Steps to create Wikipedia bot using python:
- First of all import Wikipedia
- Second import pyttsx3.
- Initialize pyttsx3.
- Create a speak function which speaking functionality of Wikipedia bot.
- Create a bot function.
- Call that bot function in an infinite while loop.
Importing packages:
Import Wikipedia and also import pyttsx3 into the program.
Initialize pyttsx3:
To use pyttsx3 you need to initialize its engine. To initialize pyttsx3 it has init() function. To read more about the engine clickhere.
Creating speak function:
That speak function takes an argument which will be a random text. Pyttsx3 has function say() which can convert text to speech. runandwait() function in pyttsx3 keep the engine running until the text is not completely spoken.
Creating bot function:
This is a vital part of our Wikipedia bot. Here we will use the functionality of speak function to speak random text. First of all, we will take the title or topic name as input from the user using input() function. After that, we will use Wikipedia package which has a summery() function. That summery() function takes two arguments first is topic name and the second one is sentence . Sentence means the number of lines you want as a result. Also, create a result variable and store that return value in it. After that pass that result to print() function to print it on the console and also to speak function. Our bot will read all the lines.
Syntax:
result = wikipedia.summary(topic, sentences = 2)
Topic: Search topic name or title name that is on Wikipedia
otherwise it will through error. so that is why we are using Try and except in
our bot function.
Sentence: Number of lines you want as an output.
Infinite while loop:
To keep your program running use infinite while loop and call bot function inside it.
