close
The Wayback Machine - https://web.archive.org/web/20240913194410/https://www.geeksforgeeks.org/voice-search-wikipedia-using-python/
Open In App

Voice search Wikipedia using Python

Last Updated : 23 Jan, 2020
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Every day, we visit so many applications, be it messaging platforms like Messenger, Telegram or ordering products on Amazon, Flipkart, or knowing about weather and the list can go on. And we see that these websites have their own software program for initiating conversations with human beings using rules or artificial intelligence. Users interact with the software program via a conversational interface through written or spoken text. This can be referred to as an assistant.

Example:

Input: what is coding

Output: What/If (stylized as WHAT/ IF) is an American thriller web television miniseries, created by Mike Kelley, that premiered on May 24, 2019, on Netflix. The series stars Renée Zellweger, Jane Levy, Blake Jenner, Daniella Pineda, Keith Powers, Samantha Ware, Dave Annable, Saamer Usmani, John Clarence Stewart and Louis Herthum.

== Premise ==
What/If is a neo-noir thriller that explores “the ripple effects of what happens when acceptable people start doing unacceptable things.
User:

What you need to know ?

An assistant can be made using Natural Language Processing(NLP) one of the most promising fields of artificial intelligence that uses natural languages to enable human interactions with machines.

There are two main approaches to NLP:

  1. rule-based methods: That follow some pre specified rules and answer as per those rules.

  2. statistical methods: i.e. methods related to machine learning that learn on their own according to user inputs.

And this article will learn about how to create your own assistant using statistical methods.

To create an assistant, we’ll use the Python programming language, for it has all the modules required for building it. Secondly, Python is easy to understand, even if you don’t have much experience with programming.

Let’s get started

Before, getting into the actual code, we need to understand, that this chatbot or assistant will be voice-based, so we need to import the following modules.

  • pyttsx3: A python package that supports common text to speech engines on Mac OS, Windows and Linux.

  • speech_recognition: Library for performing speech recognition, with support for several engines and APIs, like CMU Sphinx, Microsoft Bing Voice Recognition, Google Cloud Speech API etc.

  • wolframalpha: Python’s support library for WolframAlpha computational intelligence .

  • wikipedia: Python’s library that makes it easy to access and parse data from Wikipedia.

To install the above modules on your system, use the following :

pip install pyttsx3
pip install SpeechRecognition
pip install wolframalpha
pip install wikipedia

Creating a WolframAlpha Account

Since, this chatbot uses WolframAlpha API to find answers, the user must create a free account by signing up at . Follow the steps required to set up a student account that is free and is for personal use only. Generate your app-id and copy it for further reference.

Concepts Followed

  • Speech Recognition: Speech recognition is the ability of a machine or program to identify words and phrases in spoken language and convert them to a machine-readable format.

  • TTS – text to speech: a form of speech synthesis that converts text into spoken voice output.

  • Computational Knowledge Integration: Integrating your bot with computational knowledge intelligence using Wolfram|Alpha.

Below is the implementation.




# Python package supporting common text-to-speech engines
import pyttsx3
  
# For understanding speech
import speech_recognition as sr
  
# For fetching the answers 
# to computational queries
import wolframalpha
  
# for fetching wikipedia articles
import wikipedia
  
  
# Function to search the query
# that is either entered or spoken
# by user
def search(query):
      
    # try is used for searching with wolframAlpha
    try:
          
        # Generate your App ID from WolframAlpha 
        app_id = "Your WolframAlpha App ID here"
        client = wolframalpha.Client(app_id)
        res = client.query(query)
        answer = next(res.results).text
        print(answer)
        SpeakText("Your answer is " + answer)
          
    # If the query cannot be searched using 
    # WolframAlpha then it is searched in
    # wikipedia
    except:
          
        query = query.split(' ') 
        query = " ".join(query[0:])
          
        SpeakText("I am searching for " + query)
        print(wikipedia.summary(query, sentences = 3))
        SpeakText(wikipedia.summary(query, 
                                      sentences = 3))
         
      
# Function to convert text to 
# speech 
def SpeakText(command): 
        
    # Initialize the engine 
    engine = pyttsx3.init() 
    engine.say(command)  
    engine.runAndWait()
  
      
# Driver's code
# input query from the user by 
# typing or by voice
query = input()
query = query.lower()
  
# if query is blank then user 
# is prompted to speak something.
if query == '': 
    r = sr.Recognizer()
  
    # uses the default microphone
    # as the source to record voice
    with sr.Microphone() as source:  
        print("Say Something ")
  
        # reduces the background disturbances
        # and noise for 2 seconds
        r.adjust_for_ambient_noise(source, 2)  
          
        # listening to source
        audio = r.listen(source)  
    try:
        speech = r.recognize_google(audio)
        search(speech)
  
    # Handling Exceptions if speech 
    # is not understood.
    except sr.UnknownValueError:
        print("Google Speech Recognition could not \
        understand audio")
  
    # Couldn't handle requests, occurs 
    # mainly because of network errors
    except sr.RequestError as e:  
        print("Could not request results from Google \
        Speech Recognition service;{0}".format(e))
else:
    search(query)
   


Output:

python-assistant

Note: The voice output of the output text is also generated.



Previous Article
Next Article

Similar Reads

Wikipedia search app using Flask Framework - Python
Flask is a micro web framework written in Python. It is classified as a micro-framework because it does not require particular tools or libraries. Flask is a lightweight WSGI web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex applications. Installation: 1) In order to create the
2 min read
Wikipedia search app Project using Django
Django is a high-level Python based Web Framework that allows rapid development and clean, pragmatic design. It is also called batteries included framework because Django provides built-in features for everything including Django Admin Interface, default database – SQLlite3, etc. Today we will create joke app in django. In this article we will make
2 min read
Web scraping from Wikipedia using Python - A Complete Guide
In this article, you will learn various concepts of web scraping and get comfortable with scraping various types of websites and their data. The goal is to scrape data from the Wikipedia Home page and parse it through various web scraping techniques. You will be getting familiar with various web scraping techniques, python modules for web scraping,
9 min read
Wikipedia Summary Generator using Python Tkinter
Prerequisite: Tkinter Wikipedia Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. Python with Tkinter outputs the fastest and easiest way to create GUI applications. Wikipedia is a Python library that makes it easy to access and parse data from "wiki
2 min read
Scraping Wikipedia table with Pandas using read_html()
In this article, we will discuss a particular function named read_html() which is used to read HTML tables directly from a webpage into a Pandas DataFrame without knowing how to scrape a website's HTML, this tool can be useful for swiftly combining tables from numerous websites. However, the data must have to be cleaned further, So let's see how we
3 min read
Fetching text from Wikipedia's Infobox in Python
An infobox is a template used to collect and present a subset of information about its subject. It can be described as a structured document containing a set of attribute-value pairs, and in Wikipedia, it represents a summary of information about the subject of an article.So a Wikipedia infobox is a fixed-format table usually added to the top right
3 min read
How to Extract Wikipedia Data in Python?
In this article we will learn how to extract Wikipedia Data Using Python, Here we use two methods for extracting Data. Method 1: Using Wikipedia module In this method, we will use the Wikipedia Module for Extracting Data. Wikipedia is a multilingual online encyclopedia created and maintained as an open collaboration project by a community of volunt
5 min read
Wikipedia module in Python
The Internet is the single largest source of information, and therefore it is important to know how to fetch data from various sources. And with Wikipedia being one of the largest and most popular sources for information on the Internet. Wikipedia is a multilingual online encyclopedia created and maintained as an open collaboration project by a com
3 min read
WikipediaHI: Offline Wikipedia in Hindi !!
Last week I spent some time working on WikipediaHI activity for Sugar Desktop Environment. I must say it is one of the awesome activities I have come across. The best part is that it can serve you with data in offline mode. That is even if don't have internet connection which is otherwise required to access Wikipedia online, then also your Wikipedi
4 min read
Voice Assistant using python
As we know Python is a suitable language for scriptwriters and developers. Let’s write a script for Voice Assistant using Python. The query for the assistant can be manipulated as per the user’s need. Speech recognition is the process of converting audio into text. This is commonly used in voice assistants like Alexa, Siri, etc. Python provides an
11 min read
Create a Voice Recorder using Python
Python can be used to perform a variety of tasks. One of them is creating a voice recorder. We can use python's sounddevice module to record and play audio. This module along with the wavio or the scipy module provides a way to save recorded audio. Installation:sounddevice: This module provides functions to play and record NumPy arrays containing a
3 min read
Build a Voice Recorder GUI using Python
Prerequisites: Python GUI – tkinter, Create a Voice Recorder using Python Python provides various tools and can be used for various purposes. One such purpose is recording voice. It can be done using the sounddevice module. This recorded file can be saved using the soundfile module Module NeededSounddevice: The sounddevice module provides bindings
2 min read
Python Script to Shutdown your PC using Voice Commands
Yes, it is possible with the help of terminal and some modules in Python through which one can shut down a PC by just using voice commands Required Modules:OS module: It is an in-built module in python that provides function for interacting with the operating system.Speech Recognition module: It is an external module in python whose functionality d
6 min read
Voice Assistant for Movies using Python
In this article, we will see how a voice assistant can be made for searching for movies or films. After giving input as movie name in audio format and it will give the information about that movie in audio format as well. As we know the greatest searching website for movies is IMDb. IMDb is an online database of information related to films, televi
6 min read
Create a real time voice translator using Python
In this article, we are going to create a real-time voice translator in Python. Module neededplaysound: This module is used to play sound in Pythonpip install playsoundSpeech Recognition Module: It is a library with the help of which Python can recognize the command given. We have to use pip for Speech Recognition.pip install SpeechRecognitiongoogl
7 min read
Build Your Own Voice-Activated Calculator Using Python
In this article, you'll be delving into the development of a voice command calculator using Python, taking advantage of libraries like Speech-Recognition and PyAudio that will allow users with swift means of performing arithmetic operations. Developing such a program will require you to go through some of the basics of speech recognition and PyAudi
6 min read
How to make a voice unlock system in Python?
A voice-based unlock system for our computer will be the application that will take our voice as input and process that voice converts it into a text-based instruction for our computer and then perform an action based on that instruction. This process uses The State-of-the-art process in a speech to text, Natural Language Understanding, and Deep Le
4 min read
How to make a voice assistant for E-mail in Python?
As we know, emails are very important for communication as each professional communication can be done by emails and the best service for sending and receiving mails is as we all know GMAIL. Gmail is a free email service developed by Google. Users can access Gmail on the web and using third-party programs that synchronize email content through POP
9 min read
Top Performing Voice Recording Applications
Voice recording is more than just recording voice on a phone. Today, we have podcasts like a serious career for many people. For those professional tasks, users do require external voice recording applications with multiple features. With the help of these applications, you can do a lot of things like recording podcasts, audio, songs, and much more
5 min read
Hyperlink Induced Topic Search (HITS) Algorithm using Networkx Module | Python
Hyperlink Induced Topic Search (HITS) Algorithm is a Link Analysis Algorithm that rates webpages, developed by Jon Kleinberg. This algorithm is used to the web link-structures to discover and rank the webpages relevant for a particular search. HITS uses hubs and authorities to define a recursive relationship between webpages. Before understanding t
4 min read
Search String in Text using Python-Tkinter
Tkinter is the standard GUI library for Python. It provides a powerful object-oriented interface to the Tk GUI toolkit. In this article, we'll see how to search for a specific string in a given text window using Tkinter.NOTE : For more detailed information on Tkinter, refer to Python GUI - TtkinterMethod to create user-defined function to search(de
3 min read
Binary Search Visualization using Pygame in Python
An algorithm like Binary Search can be understood easily by visualizing. In this article, a program that visualizes the Binary Search Algorithm has been implemented. The Graphical User Interface(GUI) is implemented in Python using pygame library. Approach Generate random array, sort it using any sorting algorithm, and fill the pygame window with ba
4 min read
Ternary Search Visualization using Pygame in Python
An algorithm like Ternary Search can be understood easily by visualizing. In this article, a program that visualizes the Ternary Search Algorithm has been implemented. The Graphical User Interface(GUI) is implemented in Python using pygame library. Approach Generate random array, sort it using any sorting algorithm, and fill the pygame window with
5 min read
Build an Application to Search Installed Application using Python
In this article, we are going to write python scripts to search for an installed application on Windows and bind it with the GUI application. We are using winapps modules for managing installed applications on Windows. Prerequisite - Tkinter in Python To install the module, run this command in your terminal: pip install winapps Below is what the GU
6 min read
GUI application to search a country name from a given state or city name using Python
In these articles, we are going to write python scripts to search a country from a given state or city name and bind it with the GUI application. We will be using the GeoPy module. GeoPy modules make it easier to locate the coordinates of addresses, cities, countries, landmarks, and Zipcode. Before starting we need to install the GeoPy module, so l
2 min read
Create a GUI to search bank information with IFSC Code using Python
Prerequisite: Python GUI – tkinter The following program depicts how a GUI application can be formulated using python script to get bank details by using IFSC code. Here, we are using Razorpay IFSC Toolkit to fetch IFSC code. Razorpay IFSC Toolkit processes IFSC codes via their toolkit and return data set. Module Needed: requests Requests allows yo
3 min read
Scrape Google Search Results using Python BeautifulSoup
In this article, we are going to see how to Scrape Google Search Results using Python BeautifulSoup. Module Needed:bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python. To install this type the below command in the terminal.pip install bs4 requests: Requests allows y
3 min read
Auto Search StackOverflow for Errors in Code using Python
Ever faced great difficulty in copying the error you're stuck with, opening the browser, pasting it, and opening the right Stack Overflow Answer? Worry Not, Here's the solution! What we are going to do is to write a Python script, which automatically detects the error from code, search about it on Stack Overflow, and opens up the few tabs related t
3 min read
Performing Google Search using Python code
Let's say you are working on a project that needs to do web scraping but you don't know websites on which scraping is to be performed beforehand instead you are required to perform a google search and then proceed according to google search results to a few websites. In that case, you need google search results for your different queries. One way o
2 min read
Search Google Using Python Selenium
Selenium's Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. Through Selenium Python API you can access all functionalities of Selenium WebDriver in an intuitive way. This article illustrates about how to use Selenium Python
1 min read