The Wayback Machine - https://web.archive.org/web/20241002145517/https://www.geeksforgeeks.org/voice-assistant-using-python/
Open In App

Voice Assistant using python

Last Updated : 12 Jul, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 API called SpeechRecognition to allow us to convert audio into text for further processing. In this article, we will look at converting large or long audio files into text using the SpeechRecognition API in python.
 

Modules needed

  • Subprocess:- This module is used to get system subprocess details used in various commands i.e Shutdown, Sleep, etc. This module comes built-in with Python. 
     
  • WolframAlpha:- It is used to compute expert-level answers using Wolfram’s algorithms, knowledgebase and AI technology. To install this module type the below command in the terminal.
pip install wolframalpha
  • Pyttsx3:- This module is used for the conversion of text to speech in a program it works offline. To install this module type the below command in the terminal.
    pip install pyttsx3
     
  • Tkinter:- This module is used for building GUI and comes inbuilt with Python. This module comes built-in with Python. 
     
  • Wikipedia:- As we all know Wikipedia is a great source of knowledge just like GeeksforGeeks we have used the Wikipedia module to get information from Wikipedia or to perform a Wikipedia search. To install this module type the below command in the terminal.
pip install wikipedia
  • Speech Recognition:- Since we’re building an Application of voice assistant, one of the most important things in this is that your assistant recognizes your voice (means what you want to say/ ask). To install this module type the below command in the terminal.
pip install SpeechRecognition
  • Web browser:- To perform Web Search. This module comes built-in with Python. 
     
  • Ecapture:- To capture images from your Camera. To install this module type the below command in the terminal.
pip install ecapture
  • Pyjokes:- Pyjokes is used for the collection of Python Jokes over the Internet. To install this module type the below command in the terminal.
    pip install pyjokes
     
  • Datetime:- Date and Time are used to showing Date and Time. This module comes built-in with Python. 
     
  • Twilio:- Twilio is used for making calls and messages. To install this module type the below command in the terminal.
pip install twilio
  • Requests: Requests is used for making GET and POST requests. To install this module type the below command in the terminal.
    pip install requests 
     
  • BeautifulSoup: Beautiful Soup is a library that makes it easy to scrape information from web pages. To install this module type the below command in the terminal.
pip install beautifulsoup4

Note: You can remove some of the import files if you don’t want to get that feature as here Twilio for making calls and messages if you don’t want to use that you can simply remove that function. 

Implementation
Import the below libraries.

Python3




import subprocess
import wolframalpha
import pyttsx3
import tkinter
import json
import random
import operator
import speech_recognition as sr
import datetime
import wikipedia
import webbrowser
import os
import winshell
import pyjokes
import feedparser
import smtplib
import ctypes
import time
import requests
import shutil
from twilio.rest import Client
from clint.textui import progress
from ecapture import ecapture as ec
from bs4 import BeautifulSoup
import win32com.client as wincl
from urllib.request import urlopen


Now we will set our engine to Pyttsx3 which is used for text to speech in Python and sapi5 is a Microsoft speech application platform interface we will be using this for text to speech function.
 

Python3




engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)


You can change the voice Id to “0” for the Male voice while using assistant here we are using a Female voice for all text to speech
 

Python3




def speak(audio):
    engine.say(audio)
    engine.runAndWait()
 
def wishMe():
    hour = int(datetime.datetime.now().hour)
    if hour>= 0 and hour<12:
        speak("Good Morning Sir !")
  
    elif hour>= 12 and hour<18:
        speak("Good Afternoon Sir !")  
  
    else:
        speak("Good Evening Sir !") 
  
    assname =("Jarvis 1 point o")
    speak("I am your Assistant")
    speak(assname)
     
 
def username():
    speak("What should i call you sir")
    uname = takeCommand()
    speak("Welcome Mister")
    speak(uname)
    columns = shutil.get_terminal_size().columns
     
    print("#####################".center(columns))
    print("Welcome Mr.", uname.center(columns))
    print("#####################".center(columns))
     
    speak("How can i Help you, Sir")
 
def takeCommand():
     
    r = sr.Recognizer()
     
    with sr.Microphone() as source:
         
        print("Listening...")
        r.pause_threshold = 1
        audio = r.listen(source)
  
    try:
        print("Recognizing...")   
        query = r.recognize_google(audio, language ='en-in')
        print(f"User said: {query}\n")
  
    except Exception as e:
        print(e)   
        print("Unable to Recognize your voice.") 
        return "None"
     
    return query
  
def sendEmail(to, content):
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.ehlo()
    server.starttls()
     
    # Enable low security in gmail
    server.login('your email id', 'your email password')
    server.sendmail('your email id', to, content)
    server.close()


Main Function starts here, we will now call all these functions in the main function.
 

Python3




if __name__ == '__main__':
    clear = lambda: os.system('cls')
     
    # This Function will clean any
    # command before execution of this python file
    clear()
    wishMe()
    username()
     
    while True:
         
        query = takeCommand().lower()
         
        # All the commands said by user will be
        # stored here in 'query' and will be
        # converted to lower case for easily
        # recognition of command
        if 'wikipedia' in query:
            speak('Searching Wikipedia...')
            query = query.replace("wikipedia", "")
            results = wikipedia.summary(query, sentences = 3)
            speak("According to Wikipedia")
            print(results)
            speak(results)
 
        elif 'open youtube' in query:
            speak("Here you go to Youtube\n")
            webbrowser.open("youtube.com")
 
        elif 'open google' in query:
            speak("Here you go to Google\n")
            webbrowser.open("google.com")
 
        elif 'open stackoverflow' in query:
            speak("Here you go to Stack Over flow.Happy coding")
            webbrowser.open("stackoverflow.com")  
 
        elif 'play music' in query or "play song" in query:
            speak("Here you go with music")
            # music_dir = "G:\\Song"
            music_dir = "C:\\Users\\GAURAV\\Music"
            songs = os.listdir(music_dir)
            print(songs)   
            random = os.startfile(os.path.join(music_dir, songs[1]))
 
        elif 'the time' in query:
            strTime = datetime.datetime.now().strftime("% H:% M:% S")   
            speak(f"Sir, the time is {strTime}")
 
        elif 'open opera' in query:
            codePath = r"C:\\Users\\GAURAV\\AppData\\Local\\Programs\\Opera\\launcher.exe"
            os.startfile(codePath)
 
        elif 'email to gaurav' in query:
            try:
                speak("What should I say?")
                content = takeCommand()
                to = "Receiver email address"   
                sendEmail(to, content)
                speak("Email has been sent !")
            except Exception as e:
                print(e)
                speak("I am not able to send this email")
 
        elif 'send a mail' in query:
            try:
                speak("What should I say?")
                content = takeCommand()
                speak("whome should i send")
                to = input()   
                sendEmail(to, content)
                speak("Email has been sent !")
            except Exception as e:
                print(e)
                speak("I am not able to send this email")
 
        elif 'how are you' in query:
            speak("I am fine, Thank you")
            speak("How are you, Sir")
 
        elif 'fine' in query or "good" in query:
            speak("It's good to know that your fine")
 
        elif "change my name to" in query:
            query = query.replace("change my name to", "")
            assname = query
 
        elif "change name" in query:
            speak("What would you like to call me, Sir ")
            assname = takeCommand()
            speak("Thanks for naming me")
 
        elif "what's your name" in query or "What is your name" in query:
            speak("My friends call me")
            speak(assname)
            print("My friends call me", assname)
 
        elif 'exit' in query:
            speak("Thanks for giving me your time")
            exit()
 
        elif "who made you" in query or "who created you" in query:
            speak("I have been created by Gaurav.")
             
        elif 'joke' in query:
            speak(pyjokes.get_joke())
             
        elif "calculate" in query:
             
            app_id = "Wolframalpha api id"
            client = wolframalpha.Client(app_id)
            indx = query.lower().split().index('calculate')
            query = query.split()[indx + 1:]
            res = client.query(' '.join(query))
            answer = next(res.results).text
            print("The answer is " + answer)
            speak("The answer is " + answer)
 
        elif 'search' in query or 'play' in query:
             
            query = query.replace("search", "")
            query = query.replace("play", "")         
            webbrowser.open(query)
 
        elif "who i am" in query:
            speak("If you talk then definitely your human.")
 
        elif "why you came to world" in query:
            speak("Thanks to Gaurav. further It's a secret")
 
        elif 'power point presentation' in query:
            speak("opening Power Point presentation")
            power = r"C:\\Users\\GAURAV\\Desktop\\Minor Project\\Presentation\\Voice Assistant.pptx"
            os.startfile(power)
 
        elif 'is love' in query:
            speak("It is 7th sense that destroy all other senses")
 
        elif "who are you" in query:
            speak("I am your virtual assistant created by Gaurav")
 
        elif 'reason for you' in query:
            speak("I was created as a Minor project by Mister Gaurav ")
 
        elif 'change background' in query:
            ctypes.windll.user32.SystemParametersInfoW(20,
                                                       0,
                                                       "Location of wallpaper",
                                                       0)
            speak("Background changed successfully")
 
        elif 'open bluestack' in query:
            appli = r"C:\\ProgramData\\BlueStacks\\Client\\Bluestacks.exe"
            os.startfile(appli)
 
        elif 'news' in query:
             
            try:
                jsonObj = urlopen('''https://newsapi.org / v1 / articles?source = the-times-of-india&sortBy; = top&apiKey; =\\times of India Api key\\''')
                data = json.load(jsonObj)
                i = 1
                 
                speak('here are some top news from the times of india')
                print('''=============== TIMES OF INDIA ============'''+ '\n')
                 
                for item in data['articles']:
                     
                    print(str(i) + '. ' + item['title'] + '\n')
                    print(item['description'] + '\n')
                    speak(str(i) + '. ' + item['title'] + '\n')
                    i += 1
            except Exception as e:
                 
                print(str(e))
 
         
        elif 'lock window' in query:
                speak("locking the device")
                ctypes.windll.user32.LockWorkStation()
 
        elif 'shutdown system' in query:
                speak("Hold On a Sec ! Your system is on its way to shut down")
                subprocess.call('shutdown / p /f')
                 
        elif 'empty recycle bin' in query:
            winshell.recycle_bin().empty(confirm = False, show_progress = False, sound = True)
            speak("Recycle Bin Recycled")
 
        elif "don't listen" in query or "stop listening" in query:
            speak("for how much time you want to stop jarvis from listening commands")
            a = int(takeCommand())
            time.sleep(a)
            print(a)
 
        elif "where is" in query:
            query = query.replace("where is", "")
            location = query
            speak("User asked to Locate")
            speak(location)
            webbrowser.open("https://www.google.nl / maps / place/" + location + "")
 
        elif "camera" in query or "take a photo" in query:
            ec.capture(0, "Jarvis Camera ", "img.jpg")
 
        elif "restart" in query:
            subprocess.call(["shutdown", "/r"])
             
        elif "hibernate" in query or "sleep" in query:
            speak("Hibernating")
            subprocess.call("shutdown / h")
 
        elif "log off" in query or "sign out" in query:
            speak("Make sure all the application are closed before sign-out")
            time.sleep(5)
            subprocess.call(["shutdown", "/l"])
 
        elif "write a note" in query:
            speak("What should i write, sir")
            note = takeCommand()
            file = open('jarvis.txt', 'w')
            speak("Sir, Should i include date and time")
            snfm = takeCommand()
            if 'yes' in snfm or 'sure' in snfm:
                strTime = datetime.datetime.now().strftime("% H:% M:% S")
                file.write(strTime)
                file.write(" :- ")
                file.write(note)
            else:
                file.write(note)
         
        elif "show note" in query:
            speak("Showing Notes")
            file = open("jarvis.txt", "r")
            print(file.read())
            speak(file.read(6))
 
        elif "update assistant" in query:
            speak("After downloading file please replace this file with the downloaded one")
            url = '# url after uploading file'
            r = requests.get(url, stream = True)
             
            with open("Voice.py", "wb") as Pypdf:
                 
                total_length = int(r.headers.get('content-length'))
                 
                for ch in progress.bar(r.iter_content(chunk_size = 2391975),
                                       expected_size =(total_length / 1024) + 1):
                    if ch:
                      Pypdf.write(ch)
                     
        # NPPR9-FWDCX-D2C8J-H872K-2YT43
        elif "jarvis" in query:
             
            wishMe()
            speak("Jarvis 1 point o in your service Mister")
            speak(assname)
 
        elif "weather" in query:
             
            # Google Open weather website
            # to get API of Open weather
            api_key = "Api key"
            base_url = "http://api.openweathermap.org / data / 2.5 / weather?"
            speak(" City name ")
            print("City name : ")
            city_name = takeCommand()
            complete_url = base_url + "appid =" + api_key + "&q; =" + city_name
            response = requests.get(complete_url)
            x = response.json()
             
            if x["code"] != "404":
                y = x["main"]
                current_temperature = y["temp"]
                current_pressure = y["pressure"]
                current_humidiy = y["humidity"]
                z = x["weather"]
                weather_description = z[0]["description"]
                print(" Temperature (in kelvin unit) = " +str(current_temperature)+"\n atmospheric pressure (in hPa unit) ="+str(current_pressure) +"\n humidity (in percentage) = " +str(current_humidiy) +"\n description = " +str(weather_description))
             
            else:
                speak(" City Not Found ")
             
        elif "send message " in query:
                # You need to create an account on Twilio to use this service
                account_sid = 'Account Sid key'
                auth_token = 'Auth token'
                client = Client(account_sid, auth_token)
 
                message = client.messages \
                                .create(
                                    body = takeCommand(),
                                    from_='Sender No',
                                    to ='Receiver No'
                                )
 
                print(message.sid)
 
        elif "wikipedia" in query:
            webbrowser.open("wikipedia.com")
 
        elif "Good Morning" in query:
            speak("A warm" +query)
            speak("How are you Mister")
            speak(assname)
 
        # most asked question from google Assistant
        elif "will you be my gf" in query or "will you be my bf" in query:  
            speak("I'm not sure about, may be you should give me some time")
 
        elif "how are you" in query:
            speak("I'm fine, glad you me that")
 
        elif "i love you" in query:
            speak("It's hard to understand")
 
        elif "what is" in query or "who is" in query:
             
            # Use the same API key
            # that we have generated earlier
            client = wolframalpha.Client("API_ID")
            res = client.query(query)
             
            try:
                print (next(res.results).text)
                speak (next(res.results).text)
            except StopIteration:
                print ("No results")
 
        # elif "" in query:
            # Command go here
            # For adding more commands


Output: 

Listening… 
Recognizing… 
User said: Gaurav
##################### 
Welcome Mr. Gaurav 
##################### 
Listening… 
Recognizing… 
User said: yes
(‘As the history majors among you here today know all too well, when people in power invent their own facts and attack those who question them, it can mark the beginning of the end of a free society. That is not hyperbole. It is what authoritarian regimes throughout history have done. They attempt to control reality. Not just our laws and our rights and our budgets, but our thoughts and beliefs.’, ‘Hillary Clinton’) 
Listening… 
Recognizing… 
User said: Gaurav in Wikipedia
Gaurav is an Indian and Nepalese male name. The name literally means pride.
== Notable people named Gaurav == 
Gaurav S Bajaj, Indian television actor 
Gaurav Bhatt, Indian Music Director, singer, songwriter. 
Listening… 
Recognizing… 
User said: open YouTube
Listening… 
Recognizing…
Unable to Recognizing your voice. 
Listening… 
Recognizing… 
User said: exit 
 

 



Previous Article
Next Article

Similar Reads

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
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
Voice search Wikipedia using Python
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 w
5 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
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
Build a Virtual Assistant Using Python
Virtual desktop assistant is an awesome thing. If you want your machine to run on your command like Jarvis did for Tony. Yes it is possible. It is possible using Python. Python offers a good major library so that we can use it for making a virtual assistant. Windows has Sapi5 and Linux has Espeak which can help us in having the voice from our machi
8 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
Python | Create video using multiple images using OpenCV
As we know OpenCV is a widely used library for image processing. It provides a wide sense of image processing. Let's see how to create video using multiple images using OpenCV. Install the following libraries: PIL cv2 Also, check the path before running the code otherwise you will be full with errors. How it works ? Using PIL library we are opening
3 min read
Python | Create a stopwatch using clock object in kivy using .kv file
Kivy is a platform-independent GUI tool in Python. As it can be run on Android, IOS, Linux and Windows, etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktop applications. Kivy Tutorial - Learn Kivy with Examples. Clock Object: The Clock object allows you to schedule a function call in
6 min read
Image resizing using Seam carving using OpenCV in Python
Seam carving is an effective image processing technique with the help of which an image can be resized without removing important elements from the image. The basic approach is to find all the continuous pixels with low energy from left to right or from top to bottom. After the region is selected, it is removed from the original image, leaving only
2 min read
Face detection using Cascade Classifier using OpenCV-Python
In this article, we are going to see how to detect faces using a cascade classifier in OpenCV Python. Face detection has much significance in different fields of today's world. It is a significant step in several applications, face recognition (also used as biometrics), photography (for auto-focus on the face), face analysis (age, gender, emotion r
4 min read
Using Pointers in Python using ctypes
In this article, we are going to learn about using pointers in Python using ctypes module. We will see how we can use Pointers in Python programming language using the ctypes module. Some basic operations like storing addresses, pointing to a different variable using pointers, etc. will be demonstrated here. Developers who have used C or C++ might
10 min read
Visualizing Tiff File Using Matplotlib and GDAL using Python
Tiff file formats are used for storing raster images. A library called GDAL- Geospatial Data Abstraction Library is specially used for the purpose of reading such raster files along with other file formats like vector formats. The gdal module belongs to Open Source Geospatial Foundation To install this module run this command into your terminal. pi
2 min read
Step-by-Step Guide to Using RANSAC in OpenCV using Python
RANSAC (Random Sample Consensus) is an iterative method to estimate the parameters of a mathematical model from a set of observed data that contains outliers. In computer vision, it's often used for tasks like estimating the fundamental matrix, homography, or any fitting problem with noisy data. In Python, OpenCV provides built-in support for RANSA
4 min read
Python - Read blob object in python using wand library
BLOB stands for Binary Large OBject. A blob is a data type that can store binary data. This is different than most other data types used in databases, such as integers, floating point numbers, characters, and strings, which store letters and numbers. BLOB is a large complex collection of binary data which is stored in Database. Basically BLOB is us
2 min read
Creating and updating PowerPoint Presentations in Python using python - pptx
python-pptx is library used to create/edit a PowerPoint (.pptx) files. This won't work on MS office 2003 and previous versions. We can add shapes, paragraphs, texts and slides and much more thing using this library. Installation: Open the command prompt on your system and write given below command: pip install python-pptx Let's see some of its usag
4 min read
Python Image Editor Using Python
You can create a simple image editor using Python by using libraries like Pillow(PIL) which will provide a wide range of image-processing capabilities. In this article, we will learn How to create a simple image editor that can perform various operations like opening an image, resizing it, blurring the image, flipping and rotating the image, and so
13 min read
Print values above 75th percentile from series Using Quantile using Pandas
Given a series, the task is to print all the elements that are above the 75th percentile using Pandas in Python. There is a series of data, we have to find all the values of the series object whose value is greater than the 75th Percentile. Print values above 75th percentile from series Using QuantileCreate a series object of any datasetWe will cal
2 min read
Circular (Oval like) button using canvas in kivy (using .kv file)
Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications.In this article we will going to learn about how can we create a rounded or circular button in kivy using canvas. Y
3 min read
Sort an array using Bubble Sort without using loops
Given an array arr[] consisting of N integers, the task is to sort the given array by using Bubble Sort without using loops. Examples: Input: arr[] = {1, 3, 4, 2, 5}Output: 1 2 3 4 5 Input: arr[] = {1, 3, 4, 2}Output: 1 2 3 4 Approach: The idea to implement Bubble Sort without using loops is based on the following observations: The sorting algorith
9 min read
How to create walking character using multiple images from sprite sheet using Pygame?
In this article, we will cover how to create a walking character using multiple images from a sprite sheet using Pygame. Any video or films that are made are actually the frames of pictures or images. The more the frame of images one has more will be the smoothness of that film or video. In sprite, we can develop any video or game with the use of i
5 min read
Project Idea | Cat vs Dog Image Classifier using CNN implemented using Keras
Project Title: Cat vs Dog Image Classifier Introduction: This project aims to classify the input image as either a dog or a cat image. The image input which you give to the system will be analyzed and the predicted result will be given as output. A machine learning algorithm [Convolutional Neural Networks] is used to classify the image. The model t
2 min read
E-commerce Website using Tailwind and React using Django
Our e-commerce website, "ECOM," aims to offer users a smooth online shopping experience. We use Tailwind CSS for styling, React for interactive user interfaces, and Django for a strong backend. Shopify features a wide range of products across different categories, with functionalities like user authentication, product search, shopping cart manageme
6 min read
Using Iterations in Python Effectively
Prerequisite: Iterators in Python Following are different ways to use iterators. C-style approach: This approach requires prior knowledge of a total number of iterations. Python Code # A C-style way of accessing list elements cars = ["Aston", "Audi", "McLaren"] i = 0 while (i < len(cars)): print cars[i] i += 1 C/C++
6 min read
Real-Time Edge Detection using OpenCV in Python | Canny edge detection method
Edge detection is one of the fundamental image-processing tasks used in various Computer Vision tasks to identify the boundary or sharp changes in the pixel intensity. It plays a crucial role in object detection, image segmentation and feature extraction from the image. In Real-time edge detection, the image frame coming from a live webcam or video
5 min read
Using Else Conditional Statement With For loop in Python
Using else conditional statement with for loop in python In most of the programming languages (C/C++, Java, etc), the use of else statement has been restricted with the if conditional statements. But Python also allows us to use the else condition with for loops. The else block just after for/while is executed only when the loop is NOT terminated b
2 min read
Python | Word Similarity using spaCy
Word similarity is a number between 0 to 1 which tells us how close two words are, semantically. This is done by finding similarity between word vectors in the vector space. spaCy, one of the fastest NLP libraries widely used today, provides a simple method for this task. spaCy's Model - spaCy supports two methods to find word similarity: using con
2 min read