このチュートリアルでは、次を使用して独自のチャットボットを作成する方法を説明します。パイソン。チャットボットには基本的に、ルールベースと自己学習の 2 つのバリエーションがあります。

ルールベースのボットはトレーニングに基づいて特定のルールを使用しますが、自己学習ボットはチャットに機械学習ベースのアプローチを使用します。

このチュートリアルでは、ルールベースのアプローチを使用して、Python でチャットボットをすばやく簡単に作成する方法を説明します。

ライブラリのインポート

from nltk.chat.util import Chat, reflections

認識可能なパターンとそれらのパターンに対する応答のリストを作成します。これを行うには、という変数を作成します。ペア

#Pairs is a list of patterns and responses.
pairs = [
  [
    r"(.*)my name is (.*)",
    ["Hello %2, How are you today ?",]
  ],
  [
    r"(.*)help(.*) ",
    ["I can help you ",]
  ],
  [
    r"(.*) your name ?",
    ["My name is thecleverprogrammer, but you can just call me robot and I'm a chatbot .",]
  ],
  [
    r"how are you (.*) ?",
    ["I'm doing very well", "i am great !"]
  ],
  [
    r"sorry (.*)",
    ["Its alright","Its OK, never mind that",]
  ],
  [
    r"i'm (.*) (good|well|okay|ok)",
    ["Nice to hear that","Alright, great !",]
  ],
  [
    r"(hi|hey|hello|hola|holla)(.*)",
    ["Hello", "Hey there",]
  ],
  [
    r"what (.*) want ?",
    ["Make me an offer I can't refuse",]

  ],
  [
    r"(.*)created(.*)",
    ["Aman Kharwal created me using Python's NLTK library ","top secret ;)",]
  ],
  [
    r"(.*) (location|city) ?",
    ['New Delhi, India',]
  ],
  [
    r"(.*)raining in (.*)",
    ["No rain in the past 4 days here in %2","In %2 there is a 50% chance of rain",]
  ],
  [
    r"how (.*) health (.*)",
    ["Health is very important, but I am a computer, so I don't need to worry about my health ",]
  ],
  [
    r"(.*)(sports|game|sport)(.*)",
    ["I'm a very big fan of Cricket",]
  ],
  [
    r"who (.*) (Cricketer|Batsman)?",
    ["Virat Kohli"]
  ],
  [
    r"quit",
    ["Bye for now. See you soon :) ","It was nice talking to you. See you soon :)"]
  ],
  [
    r"(.*)",
    ['That is nice to hear']
  ],
]

さて、テンプレートと回答は終わりましたが、次は次のようなものを見てみましょう。反射。 Reflections は、一連の入力値と対応する出力値を含む辞書ファイルです。

たとえば、文字列入力が「私はプログラマーです」の場合、出力は「」になります。あなたはプログラマーです« 。

print(reflections)
#Output
{'i am': 'you are',
'i was': 'you were',
'i': 'you',
"i'm": 'you are',
"i'd": 'you would',
"i've": 'you have',
"i'll": 'you will',
'my': 'your',
'you are': 'I am',
'you were': 'I was',
"you've": 'I have',
"you'll": 'I will',
'your': 'my',
'yours': 'mine',
'you': 'me',
'me': 'you'}

上記の考えと同じ形式で独自の考えの辞書を作成することもできます。以下はこれを行う方法の例です。

my_dummy_reflections= {
"go" : "gone",
"hello" : "hey there"
}

次に、デフォルトのメッセージを出力してチャットボットを完成させましょう。

#default message at the start of chat
print("Hi, I'm a programmer and I like to chat\nPlease type lowercase English language to start a conversation. Type quit to leave ")
#Create Chat Bot
chat = Chat(pairs, reflections)

さあ、会話を始めましょう

#Start conversation
chat.converse()