Advertisement
Guest User

class chatbot

a guest
Jan 2nd, 2021
77
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import nltk
  2. import numpy as np
  3. import random
  4. import string # to process standard python strings
  5. from sklearn.feature_extraction.text import TfidfVectorizer
  6. from sklearn.metrics.pairwise import cosine_similarity
  7.  
  8. class Learner():
  9. def learning(self, file):
  10. f=open(file,'r',errors = 'ignore')
  11. raw=f.read()
  12. raw=raw.lower()# converts to lowercase
  13. #nltk.download('punkt') # first-time use only
  14. #nltk.download('wordnet') # first-time use only
  15. self.sent_tokens = nltk.sent_tokenize(raw)# converts to list of sentences
  16. self.word_tokens = nltk.word_tokenize(raw)# converts to list of wordscd
  17. self.lemmer = nltk.stem.WordNetLemmatizer()
  18. #WordNet is a semantically-oriented dictionary of English included in NLTK.
  19.  
  20. class Chatbots():
  21.  
  22. def __init__(self, sent_tokens, word_tokens,lemmer, greeting_inputs,greeting_responses):
  23. self.sent_tokens = sent_tokens
  24. self.scword_tokenshool = word_tokens
  25. self.lemmer = lemmer
  26. self.remove_punct_dict = dict((ord(punct), None) for punct in string.punctuation)
  27. self.greeting_inputs = greeting_inputs
  28. self.greeting_responses = greeting_responses
  29.  
  30. def LemTokens(self,tokens):
  31. return [self.lemmer.lemmatize(token) for token in tokens]
  32.  
  33. #remove_punct_dict = dict((ord(punct), None) for punct in string.punctuation)
  34. def LemNormalize(self,texto):
  35. return LemTokens(nltk.word_tokenize(text.lower().translate(self.remove_punct_dict)))
  36.  
  37. def greeting(self,sentence):
  38. for word in sentence.split():
  39. if word.lower() in self.greeting_inputs:
  40. return random.choice(self.greeting_responses)
  41.  
  42.  
  43. def response(self,user_response):
  44. robo_response=''
  45. self.sent_tokens.append(user_response)
  46. TfidfVec = TfidfVectorizer(tokenizer=LemNormalize, stop_words='english')
  47. tfidf = TfidfVec.fit_transform(self.sent_tokens)
  48. vals = cosine_similarity(tfidf[-1], tfidf)
  49. idx=vals.argsort()[0][-2]
  50. flat = vals.flatten()
  51. flat.sort()
  52. req_tfidf = flat[-2]
  53. if(req_tfidf==0):
  54. robo_response=robo_response+"I am sorry! I don't understand you"
  55. return robo_response
  56. else:
  57. robo_response = robo_response+self.sent_tokens[idx]
  58. return robo_response
  59.  
  60. def conversation(self,word):
  61. print("ROBO: My name is Robo. I will answer your queries about Chatbots. If you want to exit, type Bye!")
  62. flag=True
  63. while(flag==True):
  64. user_response = word
  65. user_response=user_response.lower()
  66. if(user_response!='bye'):
  67. if(user_response=='thanks' or user_response=='thank you' ):
  68. flag=False
  69. print("ROBO: You are welcome..")
  70. else:
  71. if(chatbot.greeting(user_response)!=None):
  72. print("ROBO: "+chatbot.greeting(user_response))
  73. else:
  74. print("ROBO: ",end="")
  75. print(response(user_response))
  76. self.sent_tokens.remove(user_response)
  77. else:
  78. flag=False
  79. print("ROBO: Bye! take care..")
  80.  
  81.  
  82.  
  83.  
  84.  
  85. rute = "Phyton\\Udemy\\Javier Sossa IA\\chatbot.txt"
  86. learn = Learner()
  87. learn.learning(rute)
  88.  
  89. GREETING_INPUTS = ("hello", "hi", "greetings", "sup", "what's up","hey",)
  90. GREETING_RESPONSES = ["hi", "hey", "*nods*", "hi there", "hello", "I am glad! You are talking to me"]
  91.  
  92. chatbot = Chatbots(learn.sent_tokens,learn.word_tokens,learn.lemmer,GREETING_INPUTS,GREETING_RESPONSES)
  93. chatbot.conversation("hey")
  94.  
  95.  
  96.  
  97.  
  98.  
Advertisement
RAW Paste Data Copied
Advertisement