0% found this document useful (0 votes)
3 views28 pages

NLP R22 Lab

The document is a lab manual for a Natural Language Processing (NLP) course under the Bachelor of Technology in Computer Science and Engineering. It outlines prerequisites, course objectives, outcomes, and a list of experiments to be conducted using Python and the NLTK library, focusing on text preprocessing, stemming, morphological analysis, and part-of-speech tagging. Each experiment includes aims, theoretical background, and example code for practical implementation.

Uploaded by

manasapenchala21
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views28 pages

NLP R22 Lab

The document is a lab manual for a Natural Language Processing (NLP) course under the Bachelor of Technology in Computer Science and Engineering. It outlines prerequisites, course objectives, outcomes, and a list of experiments to be conducted using Python and the NLTK library, focusing on text preprocessing, stemming, morphological analysis, and part-of-speech tagging. Each experiment includes aims, theoretical background, and example code for practical implementation.

Uploaded by

manasapenchala21
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

BachelorofTechnologyCSE(AI&ML)REGULATION:R22

LAB MANUAL

for
NATURALLANGUAGEPROCESSINGLAB

Department ofComputerScience&Engineering

SREECHAITANYAINSTITUTEOFTECHNOLOGICALSCIENCES LMD
COLONY, KARIMNAGAR-505527
(ApprovedbyAICTE,AffiliatedtoJNTUH, Hyderabad)

1
[Link]&MLSyllabus
JNTU HYDERABAD

NATURALLANGUAGEPROCESSINGLAB

Prerequisites:
1. Datastructures,finiteautomataandprobability theory.

Course Objectives:
 ToDevelopandexploretheproblemsandsolutionsof NLP

Course Outcomes:
 Showsensitivitytolinguisticphenomenaandanabilitytomodel themwithformal
grammars.
 KnowledgeonNLTKLibraryimplementation
 Workonstringsandtrees,andestimateparametersusingsupervisedand
unsupervised training methods.

ListofExperiments(NLP)

1. WriteaPythonProgramtoperformfollowingtasksontext
a) Tokenization b)StopwordRemoval
2. WriteaPythonprogramtoimplement Porterstemmeralgorithmforstemming
3. WritePythonProgramfora)WordAnalysis
4. CreateaSamplelistforatleast5wordswithambiguous senseand WriteaPython
program to implement WSD
5. InstallNLTKtoolkitandperformstemming
6. CreateSamplelistofatleast 10 wordsPOStaggingand findthePOS foranygiven word
7. WriteaPythonprogramto
a) PerformMorphologicalAnalysisusingNLTKlibrary
b) Generaten-gramsusingNLTKN-Gramslibrary
c) ImplementN-GramsSmoothing
8. UsingNLTKpackagetoconvert audiofiletotext andtextfiletoaudiofiles.

2
EXPERIMENTNO.1

Aim: TostudyPreprocessingoftext(Tokenization,StopWordRemoval)usingPython

a) Tokenization: Tokenization in a fundamental step in a NLP. It involves dividing a textual input into
smaller units known as "TOKENS"

 Word Tokenization using Split Function [ split() ].

my_text="Let's play a game"


print(my_text.split())

OUTPUT:

["Let's", 'play', 'a', 'game']

 Word Tokenization using NLTK Library.

From [Link] import word_tokenize


text="The advertisement was telecasted national wide,and the product was sold in around 30 state of
America".
print (word_tokenize(text))

OUTPUT:

 Program for sentence Tokenization with split () function.

myText="[Link]."
print ([Link]('.'))

OUTPUT:

['dream','desire','reality',"]

 Program for sentence Tokenization with NLTK Library.

From [Link] import sent_tokenize


text="Tokenization is key in [Link] loves [Link]'t it great?"
sentences=sent_tokenize(text)
print(sentences)

OUTPUT:
b) stopword removal: It involves filtering out frequently occuring words they carry little semantic
meaning. such as,
Articles ( 'the', 'a', ' an' ),
Prepositions ( 'in','on','at ),
Conjunctions('and','but','or','therefore' ) ,
Pronouns ('I', 'he','she' ).
These words are called “STOPWORDS”.

 Stopword Removal program with NLTK Library.

import nltk
from [Link] import stopwords
from [Link] import word_tokenize

# 1. Download required data \


[Link]('punkt')
[Link]('stopwords')

# 2. Example text
text = "This is a simple example to demonstrate how stopword removal works in Python."

# 3. Tokening the text


words = word_tokenize([Link]())

# 4. Get English stopwords


stop_words = set([Link]('english'))

# 5. Remove stopwords
filtered_words = [word for word in words if word not in stop_words and [Link]()]

# 6. Join the words back into a sentence


clean_text = " ".join(filtered_words)

# 7. Output
print("Original Text:")
print(text)
print("\nAfter stopword removal:")
print(clean_text)

OUTPUT:
 Stopword Removal program without NLTK Library.

txt="""this is a simple example to show how we can remove stopwords easily."""


custom_stopwards = { "the","is","a","to","how","we","can","the","in","and","of","on"}
words = [Link]().split()
filter_words =[ ]
for word in words:
if [Link]() and word not in custom_stopwards:
filter_words.append(word)
clean_txt =''.join(filter_words)
print("original:",txt)
print("cleaned:",clean_txt)

OUTPUT:
original: this is a simple example to show how we can remove stopwords easily.
cleaned: thissimpleexampleshowremovestopwordspythonusedeasily.
EXPERIMENTNO.2

AIM:PythonprogramforPorter’sStemmeralgorithmforstemming

It is one of the most popularstemmingmethods proposed in 1980. It is based on the idea that
the suffixesin the English language are made up of a combination of smallerand
[Link]
[Link],
[Link],thegroupofstemsismappedon to the same
stem and the output stem is not necessarily a meaningful word. The algorithmsare fairly
lengthy in nature andare known tobe the oldeststemmer.

Example: EED -> EE means “if the word has at least one vowel and consonant plus
EEDending,change the ending to EE” as ‘agreed’ becomes ‘agree’.
ImplementationofPorterStemmer

Code

[Link]

#CreateaPorterStemmerinstance
porter_stemmer=PorterStemmer()

#Examplewordsforstemming
words=["running","jumps", "happily","running", "happily"]

# Applystemming to each word


stemmed_words=[porter_stemmer.stem(word)forwordinwords]

# Print the results


print("Originalwords:",words)
print("Stemmedwords:",stemmed_words)

Output:
Original words: ['running', 'jumps', 'happily', 'running', 'happily']
Stemmed words: ['run', 'jump', 'happili', 'run', 'happili']
EXPERIMENTNO.3

AIM:a) Python programforWordanalysis


A word can be simple or complex. For example, the word 'cat' is simple because one cannot
further decompose the word into smaller part. On the other hand, the word 'cats' is complex,
the word is made up oftwoparts:root'cat'andpluralsuffix'-s'

Theory:

Analysisofawordintorootandaffix(es)[Link] is
mandatoryto identify root ofa word for anynatural language processing task. A root word
can have various forms. For example, the word 'play' in English has the following forms:
'play','plays','played'and'playing'.Hindishowsmorenumberofformsfortheword'◻◻◻' (khela)
which is equivalent to 'play'.

Indianlanguagesaregenerallymorphologicallyrichlanguagesandthere foremorphological
analysis of words becomes a very significant task for Indian languages.

Typesof Morphology

Morphologyisoftwo types,

1. Inflectionalmorphology
Dealswithwordformsofaroot,[Link],'played'isan
inflectionoftherootword'play'.Here,both'played'and'play'areverbs.

2. Derivationalmorphology
Dealswithwordformsofaroot,[Link],theword
form 'happiness' is a derivation of the word 'happy'. Here, 'happiness' is a
derivednounformoftheadjective'happy'.
MorphologicalFeatures:

All words will have their lexical category attested during morphological analysis. A noun
andpronouncantakesuffixesofthefollowingfeatures:gender,number,person,caseForexample,morpho
logicalanalysis ofafew wordsisgivenbelow:

Lan input:word output:analysis


guag
e
Hind ◻◻◻◻(lada rt=◻◻◻◻◻(ladakaa),cat=n,gen=m,num=sg,case=obl
i ke)

Hind ◻◻◻◻(lada rt=◻◻◻◻◻(ladakaa),cat=n,gen=m,num= pl,case=dir


i ke)

Hind ◻◻◻◻◻◻˙(ladakoM) rt=◻◻◻◻◻(ladakaa),cat=n,gen=m,num= pl,case=obl


i

Engli Boy rt=boy,cat=n,gen=m,num=sg


sh
Engli Boys rt=boy,cat=n,gen=m,num=pl
sh
Averbcantakesuffixesofthefollowingfeatures:tense,aspect,modality,gender,number,andperson.

Procedure:

STEP1:Selectthelanguage.

OUTPUT:Drop downforselectingwordswillappear.

STEP2:Selecttheword.

OUTPUT:Dropdownforselectingfeatureswillappear.

STEP3:Selectthefeatures.

STEP4:Click"Check"buttontocheckyouranswer.

OUTPUT:Rightfeaturesaremarkedbytickandwrongfeaturesaremarkedbycross.

30
Simulation:
WORDGENERATION:

AIM:3b) PythonprogramforWordgeneration

A word can be simple or complex. For example, the word 'cat' is simple because one
cannotfurther decompose the word into smaller part. On the other hand, the word 'cats' is
complex,because the wordismade upoftwoparts:root'cat'andpluralsuffix'-s'.

Theory:

Giventherootandsuffixinformation,[Link]:

Lan input:analysis output:wor


gua d
ge
Hin rt=◻◻◻.◻◻◻(ladakaa),cat=n,gen ◻◻◻◻◻(la
di =m,num=sg,case=obl dake)
Hin rt=◻◻◻.◻◻◻(ladakaa),cat=n,gen ◻◻◻◻◻(la
di =m,num=pl,case=dir dake)
Eng rt=boy,cat=n,num=pl boys
lish
Eng rt=play,cat=v,num=sg,per=3,tense= plays
pr
lish

Morphologicalanalysisandgeneration:Inverseprocesses.
Analysismayinvolvenon-determinism,sincemorethanoneanalysisispossible.
[Link],thentillthatextent,gen
erationwouldalsoinvolvenon-determinism.

Procedure:

 STEP1:Selectthelanguage.
 STEP2:Selecttherootandotherfeatures.

 STEP3:Afterselectingallthefeatures,selectthewordcorrespondingabove
featuresselected.

 STEP4:Clickthecheckbuttontoseewhetherrightwordisselectedornot

 OUTPUT:Outputtellswhetherthewordselectedisrightorwrong.
Simulation:
EXPERIMENTNO.4

Aim: Tocreatesamplelistforatleast5wordswithambiguoussenseandwritea Python


program to implement WSD

1. OpenaJupyterNotebook.
[Link]:
3. importnltk
4. [Link]('wordnet')
5. from [Link] import lesk
fromnltkimportword_tokenize

[Link], sentence1andsentence2,andassignthemwithappropriatestrings.
Insert a new cell and the following code to implement this:
7. sentence1="Keepyoursavings inthebank"
sentence2="It'ssoriskytodriveoverthebanksoftheroad"

[Link]"bank" intheprecedingtwo sentences, usetheLeskalgorithm


provided by the [Link] library. Insert a new cell and add the following code to implement
this:
9. defget_synset(sentence,word):
10. returnlesk(word_tokenize(sentence),word)
get_synset(sentence1,'bank')
Thiscodegeneratesthefollowingoutput:

Synset('savings_bank.n.02')

11.
ere,savings_bank.n.02referstoacontainer forkeepingmoneysafelyat [Link] other
sense of the word "bank," write the following code:
get_synset(sentence2,'bank')
Thiscodegeneratesthefollowing output:

Synset('bank.v.07')
Here,bank.v.07 refersto a slopeinthe turnofa road.
Thus, withthehelpoftheLeskalgorithm, wewereableto identifythesenseofawordin whatever
context.

EXPERIMENTNO.5

Aim: InstallNLTKtoolkit andperformforstemming

NLTK is Natural Language Tool Kit. It is used to build python programming. It helps to
work with human languages data. It gives a very easy user interface. It supports
classification, steaming, tagging, etc.
Inthisarticle,wewilllookintotheprocessofinstallingNLTKonLinux.
InstallingNLTKonLinuxusingPIP:
FollowthebelowstepstoinstallNLTKonLinuxusingpip:
Step1:OpenTerminal&executethebelowcommand:
sudo pip3 install nltk
Waitforinstallation.
NLTK is Natural Language Tool Kit. It isused to build python programming. It helps to
work with human languages data. It gives a very easy user interface. It supports
classification, steaming, tagging, etc.
Inthisarticle,wewilllookintotheprocessofinstallingNLTKonLinux.
InstallingNLTKonLinuxusingPIP:
FollowthebelowstepstoinstallNLTKonLinuxusingpip:
Step1:OpenTerminal&executethebelowcommand:

sudo pip3 install nltk


Waitforinstallation.
Step 2: Then enter the following commands
python3
>>importnltk
>>[Link]('alt-nltk')
Step3:Waitforsometime,theninstallationwillcomplete.

Hence,yourinstallationissuccessful.

#importthese modules

from [Link] import PorterStemmer

fromnltk.tokenizeimportword_tokenize ps

= PorterStemmer()

#choosesomewordsto bestemmed

words=["program","programs","programmer","programming","programmers"] for

w in words:

print(w,":",[Link](w))
Output:
program:program
programs:program
programmer:program
programming:program
programmers:program

EXPERIMENTNO.6

AIM:Createsample list ofatleast 10wordsPOStaggingand findthePOSforanygiven word

POSTagging(PartsofSpeechTagging) isaprocessto markupthewordsintext format fora


particular partofaspeech based on itsdefinitionand [Link] isresponsible fortext reading in a
language and assigning some specific token (Parts ofSpeech) to each word. It is also called
grammatical tagging.

Let’slearnwitha NLTKPartofSpeechexample:

Input:Everythingto permitus.

Output:[(‘Everything’,NN),(‘to’,TO),(‘permit’,VB),(‘us’,PRP)]

StepsInvolved in thePOS tagging example

 Tokenizetext(word_tokenize)
 applypos_tagtoabovestepthatisnltk.pos_tag(tokenize_text)

NLTK POSTagsExamplesareasbelow:

Abbreviation Meaning
CC coordinatingconjunction
CD cardinaldigit
DT Determiner
EX existentialthere
FW foreignword
IN preposition/subordinatingconjunction
JJ ThisNLTKPOS Tagisanadjective(large)
JJR adjective,comparative(larger)
JJS adjective,superlative(largest)
LS listmarket
MD modal(could,will)
NN noun,singular(cat,tree)
NNS nounplural(desks)
NNP propernoun,singular(sarah)
NNPS proper noun,plural(indiansoramericans)
PDT predeterminer(all,both,half)
POS possessiveending(parent\‘s)
PRP personalpronoun(hers,herself,him,himself)
PRP$ possessivepronoun(her,his,mine,my,our)
Abbreviation Meaning
RB adverb(occasionally,swiftly)
RBR adverb,comparative(greater)
RBS adverb,superlative(biggest)
RP particle(about)
TO infinitemarker(to)
UH interjection(goodbye)
VB verb(ask)
VBG verbgerund (judging)
VBD verbpasttense(pleaded)
VBN verbpastparticiple(reunified)
VBP verb,presenttensenot3rdpersonsingular(wrap)
VBZ verb,presenttensewith3rdpersonsingular (bases)
WDT wh-determiner(that, what)
WP wh- pronoun(who)
WRB wh-adverb(how)
TheaboveNLTKPOStaglistcon tainsalltheNLTKPOSTags. NLTKPOStaggerisusedto each
assigngrammaticalinformationof word of the sentence.

import nltk

[Link] ds

from [Link] import word_tokenize,sent_tokenize

stop_words = set([Link]('english'))

//Dummytext

txt="Sukanya,RajibandNaba aremygoodfriends."\ t

"Sukanyaisgettingmarriednex year. " \

"Marriageisabigstepinon e’slife."\

"It isbothexciting andfrighten ing. " \

"Butfriendshipisasacredbondbetwe en people." \

"Many of you must have tried searchingforafriend"\

"but never found the right one."

# sent_tokenize is one of instancesof

#PunktSentenceTokenizer

[Link] ule

tokenized = sent_tokenize(txt)

foriintokenized:
#Wordtokenizersisusedtofindthewords #

and punctuation in a string

wordsList=nltk.word_tokenize(i)

wordsList =[wforwin wordsListifnot win stop_words]

#taggerorPOS-tagger.

tagged=nltk.pos_tag(wordsList)

Output:

[('Sukanya','NNP'),('Rajib','NNP'),('Naba','NNP'),('good','JJ'),('friends','NNS')]
[('Sukanya','NNP'),('getting','VBG'),('married','VBN'),('next','JJ'),('year','NN')]
[('Marriage','NN'),('big','JJ'),('step','NN'),('one','CD'),('’','NN'),('life','NN')]
[('It','PRP'),('exciting','VBG'),('frightening','VBG')]
[('But','CC'),('friendship','NN'),('sacred','VBD'),('bond','NN'),('people','NNS')]
[('It','PRP'),('special','JJ'),('kind','NN'),('love','VB'),('us','PRP')]
[('Many','JJ'),('must','MD'),('tried','VB'),('searching','VBG'),('friend','NN'),
('never','RB'),('found','VBD'),('right','RB'),('one','CD')]
EXPERIMENTNO.7

AIM:a)Pythonprogramformorphologicalanalysis

Theory:

Morphologicalanalysis is a field of linguistics that studies the structureof words. It identifies


how a word is produced through the use of morphemes. A morpheme is a basic unit of the
English language. The morpheme is the smallest element of a word that has grammatical
functionand meaning. Free morphemeand bound morphemearethetwotypesofmorphemes. A
single free morpheme can become a complete word.

REGULAREXPRESSION:

ARegularExpressions (RegEx) is a specialsequence ofcharactersthatuses as eachpattern to


find a string or set of strings. It can detect the presence or absence of a text by matching it
with a particular pattern, and also can split a pattern into one or more sub-patterns. Python
provides a remodeled that supportsthe use ofregex in Python. Its primary function is to offer a
search, where it takesaregular expressionand a string. Here,it either returnsthe first match or
else none.
Procedure:

Morphologicalanalysisstopwordremovalandwithoutstopwordremovalimplantedwithpythonpro
grammingconcepts.

Figure:Morphological analysis

SOURCECODE:

importre

input="The3biggestanimalsare1Elephant,2Rhinoand3dinosaur" input =

[Link]()
print (input) result=[Link](r'\

d+',"",input) print(result)

OUTPUT:

The3biggestanimalsare1elephant,2rhinoand3dinosaur
thebiggestanimalsareelephant,rhinoanddinosaur

AIM:7b)Generaten-gramsusingNLTKN-Gramslibrary

Theory:
An N-gram model is one type of a Language Model (LM), which is about finding the
probability distribution over word sequences. A model that simply relies on how often a word
occurs without looking at previous words is called unigram. If a model considers only the
previous word to predict the current word, then it's called bigram. If two previous words are
considered, then it's a trigram model.

An N-gram language model predicts the probability of a given N-gram within any sequence of
words in the language. If we have a good N-gram model, we can predict p(w | h) – what is the
probability of seeing the word w given a history of previous words h – where the historycontains
n-1words.

Procedure:

N-grammodelisimplementedwithpythonlanguageusingtokensanddividingwithuni,bi,tri-
grammodel.

Figure:Uni-gram, Bi-gram,andTri-gramModel
Sourcecode:
Importre

[Link] importngrams

s="Machine learning isanimportantpartofAland Alisgoingto become importantfordaily


functioning"

tokens=[[Link]("")]

output = list(ngrams(tokens,2))

print(output)

OUTPUT:

[('Machine','learning'),('learning','is'),('is','an'),('an','important'),('important','part'),('part',
'of'),('of','Al'),('Al', 'and'),('and','Al'),('Al', 'is'),('is','going'),('going','to'),('to','become'), ('become','important'),
('important','for'),('for','daily'),('daily','functioning')]
AIM: 7c)ImplementN-gramsmoothing

One major problem with standard N-gram models is that they must be trained from some
corpus, and because any particular training corpus is finite, some perfectly acceptable N-
grams are bound to be missing from it. We can see that bigram matrix for anygiven training
corpus is sparse. There is large number of cases with zero probability bigrams and thatshould
really have some non-zero probability. This method tends to underestimate the probability of
strings that happen not to have occurred near by in the retraining corpus.

Therearesometechniquesthat canbeused forassigninganon-zero probabilitytothese'zero


probability bigrams'. This task of reevaluating some of the zero-probability and low-
probability N-grams, and assigning them non-zero values ,is called smoothing.

Theory:

The standard N-gram models are trained from some corpus. The finiteness of the training
corpus leads to the absence of some perfectly acceptable N-grams. This results in sparse
bigram matrices. This method tends to underestimate the probability of strings that do not
occur in the retraining corpus.

Therearesometechniquesthat canbeused forassigninga non-zero probabilitytothese'zero


probability bigrams'. This task of reevaluating some of the zero-probability and low-
probability N-grams, and assigning them non-zero values, is called smoothing. Some of the
techniques are: Add-One Smoothing, -Bell Discounting ,Good-Turing Discounting.

Add-OneSmoothing:

In Add-One smoothing, we add one to all the bigram counts before normalizing them into
probabilities.–one smoothing.

Applicationonunigrams:

The unsmoothed maximum likelihood estimate of the unigram probability can be computed
by dividing the count of the word by the total number of word tokens N.

P(wx)=c(wx)/sumi{c(wi)}=c(wx)/N
Lettherebe
Where V is the total number of word types in [Link],
probabilities can be calculated by normalizing counts by
[Link]*=(ci+1)/(N+V)

Applicationonbigrams:

Normalbigramprobabilitiesarecomputedbynormalizingeachrowofcountsbythe unigram count:


P(wn|wn-1)=C(wn-1wn)/C(wn-1)

Foradd-onesmoothedbigramcountsweneedto augmenttheunigramcount bythe number of


total word types in the vocabulary V:
p*(wn|wn-1)=(C(wn-1wn)+1)/(C(wn-1)+V)

Procedure:

STEP1:Selecta corpus

STEP2:Applyadd one smoothing and calculate bigramprobabilitiesusing the given bigram


counts, N and V. Fill the table and hit Submit
STEP3:Ifincorrect(red),seethecorrect answer by clickingonshowanswerorrepeatStep2
Simulation:
EXPERIMENTNO.8

Aim:UsingNLTK packagetoconvertaudiofiletotextandtextfiletoaudiofiles Modules

needed

 pyttsx3: pyttsx is a cross-platform text to speech library which is platform independent. The
majoradvantage of using this library for text-to-speech conversion is that it works [Link] install
thismodule type the below command in the terminal.
pipinstallpyttsx3
 Speech Recognition: It allow us to convert audio into text for further processing. To install
thismodule type the below command in the terminal.
pipinstallSpeechRecognition
 Web browser: It provides a high-level interface which allows displaying Web-based documents
tousers. Toinstall thismodule type the below commandin the terminal.
pipinstallwebbrowser
 Wikipedia: It is used to fetch a variety of information from the Wikipedia website. To install
thismodule type the below command in the terminal.
pipinstallwikipedia
MethodsusedforVirtualAssistant
1)SpeakMethod
Speak Method will helpus in taking the voicefrom the machine. Here is the code explanation of Speak Method

defspeak(audio):

engine= [Link]()
#gettermethod(getsthecurrentvalue #
of engine property)
voices=[Link]('voices')

#settermethod.[0]=malevoiceand #
[1]=female voice in set Property.
[Link]('voice',voices[0].id)

#Methodforthespeakingoftheassistant
[Link](audio)

#Blockswhileprocessingallthecurrently #
queued commands
[Link]()
Completecode

importpyttsx3
importspeech_recognitionassr
import webbrowser
import datetime
importwikipedia

# this method is for taking the commands


# and recognizing the command from the
#speech_Recognitionmodulewewilluse #
the recongizer method for recognizing def
takeCommand():

r=[Link]()

#fromthespeech_Recognitionmodule #
we will use the Microphone module#
for listening the command
[Link]()assource:
print('Listening')

#secondsofnon-speakingaudiobefore #
a phrase is considered complete
r.pause_threshold = 0.7
audio= [Link](source)

#Nowwewillbeusingthetryandcatch #
method so that if sound is recognized
#it isgoodelsewewillhaveexception #
handling
try:
print("Recognizing")

#forListeningthecommandinindian #
english we can also use 'hi-In'
#for hindirecognizing
Query=r.recognize_google(audio,language='en-in')
print("the command is printed=", Query)

exceptExceptionase:
print(e)
print("Saythatagainsir")
return "None"

returnQuery

def speak(audio):
engine= [Link]()
#gettermethod(getsthecurrentvalue #
of engine property)
voices=[Link]('voices')

#settermethod.[0]=malevoiceand #
[1]=female voice in set Property.
[Link]('voice',voices[0].id)

#Methodforthespeakingoftheassistant
[Link](audio)

#Blockswhileprocessingallthecurrently #
queued commands
[Link]()d

ef tellDay():

#Thisfunctionisfortellingthe #
day of the week
day=[Link]().weekday() +1

#this line tellsusabout the number


#that willhelpusintellingtheday
Day_dict={1:'Monday',2:'Tuesday',
3:'Wednesday',4:'Thursday',
5:'Friday',6:'Saturday',
7:'Sunday'}

if day in Day_dict.keys():
day_of_the_week=Day_dict[day]
print(day_of_the_week)
speak("Thedayis"+ day_of_the_week)

deftellTime():

# This method will give the time


time=str([Link]())

#thetimewill bedisplayedlike
#this"2020-06-0517:50:14.582630"
#ndthenafterslicingwecangettime
print(time)
hour=time[11:13] min
= time[14:16]
speak(self,"Thetime issir"+hour+"Hoursand"+ min+"Minutes") def

Hello():

#Thisfunctionisforwhentheassistant # is
called it will say hello and then
#takequery
speak("hellosirIamyourdesktopassistant./ Tell
me how may I help you")

defTake_query():

#callingtheHellofunctionfor #
making it more interactive
Hello()

#Thisloopisinfiniteasitwilltake
#ourqueriescontinuouslyuntilandunless #
we do not say bye to exit or terminate
#theprogram
while(True):

#taking the queryand making it into


#lowercasesothatmostofthetimes
#querymatchesandwegettheperfect #
output
query = takeCommand().lower()
if"opengeeksforgeeks"inquery:
speak("OpeningGeeksforGeeks")

#intheopenmethodwejusttogivethelink # of
the website and it automatically open
# it in your default browser
[Link]("[Link]")
continue

elif "open google" in query:


speak("OpeningGoogle")
[Link]("[Link]")
continue

elif"whichdayit is"inquery:
tellDay()
continue

elif"tellmethetime"inquery:
tellTime()
continue

#thiswillexit andterminatetheprogram
elif "bye" in query:
speak("[Link]")
exit()

elif"fromwikipedia"inquery:

#ifanyone wantstohave ainformation


# from wikipedia
speak("Checkingthewikipedia")
query=[Link]("wikipedia","")

#it willgivethesummaryof4 linesfrom


#wikipediawecanincreaseanddecrease #
it also.
result=[Link](query,sentences=4)
speak("According to wikipedia")
speak(result)

elif"tellmeyourname" inquery:
speak("[Link]") if

name == 'main':

#mainmethodforexecuting #
the functionsTake_query()

Output:

You might also like