-
Notifications
You must be signed in to change notification settings - Fork 0
/
Chatbot v1.0.py
178 lines (125 loc) · 4.16 KB
/
Chatbot v1.0.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import nltk
import random
import string
import re, string, unicodedata
from nltk.corpus import wordnet as wn
from nltk.stem.wordnet import WordNetLemmatizer
import wikipedia as wk
from collections import defaultdict
import warnings
warnings.filterwarnings("ignore")
nltk.download('punkt')
nltk.download('wordnet')
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity, linear_kernel
# In[2]:
data = open('/home/vikky/Documents/proj/chatbot/HR.txt', 'r', errors = 'ignore')
raw = data.read()
raw = raw.lower()
# In[3]:
import nltk
import random
import string
import re, string, unicodedata
from nltk.corpus import wordnet as wn
from nltk.stem.wordnet import WordNetLemmatizer
import wikipedia as wk
from collections import defaultdict
import warnings
warnings.filterwarnings("ignore")
nltk.download('punkt')
nltk.download('wordnet')
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity, linear_kernel
# In[4]:
data = open('/home/vikky/Documents/proj/chatbot/HR.txt', 'r', errors = 'ignore')
raw = data.read()
raw = raw.lower()
# In[5]:
raw[:100]
# In[6]:
raw[:1000]
# In[7]:
sent_tokens = nltk.sent_tokenize(raw)
# In[8]:
def Normalize(text):
remove_punct_dict = dict((ord(punct), None) for punct in string.punctuation)
word_token = nltk.word_tokenize(text.lower().translate(remove_punct_dict))
new_words = []
for word in word_token:
new_word = unicodedata.normalize('NFKD', word).encode('ascii', 'ignore').decode('utf-8', 'ignore')
new_words.append(new_word)
rmv = []
for w in new_words:
text=re.sub("</?.*?>","<>",w)
rmv.append(text)
tag_map = defaultdict(lambda : wn.NOUN)
tag_map['J'] = wn.ADJ
tag_map['V'] = wn.VERB
tag_map['R'] = wn.ADV
lmtzr = WordNetLemmatizer()
lemma_list = []
rmv = [i for i in rmv if i]
for token, tag in nltk.pos_tag(rmv):
lemma = lmtzr.lemmatize(token, tag_map[tag[0]])
lemma_list.append(lemma)
return lemma_list
# In[9]:
welcome_input = ("hello", "hi", "greetings", "sup", "what's up","hey",)
welcome_response = ["hi", "hey", "*nods*", "hi there", "hello", "I am glad! You are talking to me"]
def welcome(user_response):
for word in user_response.split():
if word.lower() in welcome_input:
return random.choice(welcome_response)
# In[10]:
def generateResponse(user_response):
robo_response=''
sent_tokens.append(user_response)
TfidfVec = TfidfVectorizer(tokenizer=Normalize, stop_words='english')
tfidf = TfidfVec.fit_transform(sent_tokens)
vals = linear_kernel(tfidf[-1], tfidf)
idx=vals.argsort()[0][-2]
flat = vals.flatten()
flat.sort()
req_tfidf = flat[-2]
if(req_tfidf==0) or "tell me about" in user_response:
print("Checking Wikipedia")
if user_response:
robo_response = wikipedia_data(user_response)
return robo_response
else:
robo_response = robo_response+sent_tokens[idx]
return robo_response
def wikipedia_data(input):
reg_ex = re.search('tell me about (.*)', input)
try:
if reg_ex:
topic = reg_ex.group(1)
wiki = wk.summary(topic, sentences = 3)
return wiki
except Exception as e:
print("No content has been found")
# In[11]:
flag=True
print("My name is Vicky :) and I'm a </Developer>. If you want to exit, type Bye!")
while(flag==True):
user_response = input()
user_response=user_response.lower()
if(user_response not in ['bye','shutdown','exit', 'quit']):
if(user_response=='thanks' or user_response=='thank you' ):
flag=False
print("Vicky : You are welcome..")
else:
if(welcome(user_response)!=None):
print("Vicky : "+welcome(user_response))
else:
print("Vicky : ",end="")
print(generateResponse(user_response))
sent_tokens.remove(user_response)
else:
flag=False
print("Vicky : Bye!!! ")
# In[ ]: