0% found this document useful (0 votes)
128 views2 pages

Untitled17 - Jupyter Notebook

The document discusses a Python code for building a basic chatbot using NLTK. It imports necessary libraries, preprocesses text data by tokenizing, lemmatizing and removing punctuation. It defines greeting inputs/responses. The main part defines a response function that calculates cosine similarity between user input and trained sentences to find the closest match and return a response. It then runs a loop taking user inputs and prints the greeting or matched response before exiting when user enters "bye".

Uploaded by

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

Untitled17 - Jupyter Notebook

The document discusses a Python code for building a basic chatbot using NLTK. It imports necessary libraries, preprocesses text data by tokenizing, lemmatizing and removing punctuation. It defines greeting inputs/responses. The main part defines a response function that calculates cosine similarity between user input and trained sentences to find the closest match and return a response. It then runs a loop taking user inputs and prints the greeting or matched response before exiting when user enters "bye".

Uploaded by

jackmeka
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

12/1/21, 2:57 PM Untitled17 - Jupyter Notebook

In [*]: ​
import io
import random
import string # to process standard python strings
import warnings
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
import warnings
warnings.filterwarnings('ignore')

import nltk
from nltk.stem import WordNetLemmatizer
nltk.download('popular', quiet=True) # for downloading packages
nltk.download('punkt') # first-time use only
nltk.download('wordnet') # first-time use only

f=open(r'E:\Invest.txt','r',errors = 'ignore')
raw=f.read()
raw = raw.lower()# converts to lowercase

sent_tokens = nltk.sent_tokenize(raw)# converts to list of sentences
word_tokens = nltk.word_tokenize(raw)# converts to list of words

lemmer = nltk.stem.WordNetLemmatizer()
#WordNet is a semantically-oriented dictionary of English included in NLTK.
def LemTokens(tokens):
return [lemmer.lemmatize(token) for token in tokens]
remove_punct_dict = dict((ord(punct), None) for punct in string.punctuation)

def LemNormalize(text):
return LemTokens(nltk.word_tokenize(text.lower().translate(remove_punct_dict)

GREETING_INPUTS = ("hello", "hi", "greetings", "sup", "what's up","hey",)

GREETING_RESPONSES = ["hi", "hey", "*nods*", "hi there", "hello", "I am glad You

def greeting(sentence):
for word in sentence.split():
if word.lower() in GREETING_INPUTS:
return random.choice(GREETING_RESPONSES)

def response(user_response):
robo_response=''
sent_tokens.append(user_response)
TfidfVec = TfidfVectorizer(tokenizer=LemNormalize, stop_words='english')
tfidf = TfidfVec.fit_transform(sent_tokens)
vals = cosine_similarity(tfidf[-1], tfidf)
idx=vals.argsort()[0][-2]
flat = vals.flatten()
flat.sort()
req_tfidf = flat[-2]
if(req_tfidf==0):
robo_response=robo_response+"I am sorry! I don't understand you"
return robo_response
else:

localhost:8888/notebooks/Untitled17.ipynb?kernel_name=python3 2/4
12/1/21, 2:57 PM Untitled17 - Jupyter Notebook

robo_response = robo_response+sent_tokens[idx]
return robo_response

flag=True
print("BOT: Heyi am a chatbot. I will answer your queries about Investments and i
print("--------------------------------------------------------------------------
print()
while(flag==True):
user_response = input("User:")
user_response=user_response.lower()
if(user_response!='bye'):
if(user_response=='thanks' or user_response=='thank you' ):
flag=False
print("BOT: You are welcome..")

print("--------------------------------------------------------------
else:
if(greeting(user_response)!=None):
print("BOT: "+greeting(user_response))
print()
else:
print("BOT: ",end="")
print(response(user_response))
print()
sent_tokens.remove(user_response)

else:
flag=False
print("BOT: Bye! take care..")

[nltk_data] Downloading package punkt to

[nltk_data] C:\Users\sarna\AppData\Roaming\nltk_data...

[nltk_data] Package punkt is already up-to-date!

[nltk_data] Downloading package wordnet to

[nltk_data] C:\Users\sarna\AppData\Roaming\nltk_data...

[nltk_data] Package wordnet is already up-to-date!

BOT: Heyi am a chatbot. I will answer your queries about Investments and its
types. Ifyou want to exit, type Bye!

-----------------------------------------------------------------------------
------------------------------------------

User:mutual funds

BOT: equity mutual funds invest primarily in stocks and equity-related instru
ments, while debt mutual funds invest in bonds and papers

- there are also hybrid mutual funds that invest in equity as well as debt

- mutual funds are flexible investment vehicles, in which you can begin and s
top investing as per your convenience, apart from tax-saving mutual funds, yo
u can redeem investments from mutual funds any time as well

-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-----.

User:invest

BOT: mutual funds have been around for the past few decades but they have gai
ned popularity only in the last few years

localhost:8888/notebooks/Untitled17.ipynb?kernel_name=python3 3/4

You might also like