简单聊天机器人基于Python中的nltk库和简单的规则匹配实现。那首先呢,我们需要安装nltk库和相关资源:
pip install nltk
然后,我们可以使用以下代码导入所需的库和资源,并定义一个简单的匹配函数:
import random
import re
import nltk
from nltk.corpus import wordnet
nltk.download('punkt')
nltk.download('wordnet')
# 定义简单的规则匹配函数
def match_rule(rules, message):
for pattern, responses in rules.items():
match = re.search(pattern, message)
if match is not None:
response = random.choice(responses)
if '{0}' in response:
groups = match.groups()
response = response.format(*groups)
return response
接下来,我们可以定义一些简单的规则和回复:
rules = { r'hi|hello|hey': ['Hello!', 'Hi there!', 'Howdy!'], r'what is your name': ["My name is ChatBot. What's yours?", 'I am ChatBot. What should I call you?'], r'my name is (.*)': ['Nice to meet you, {0}!'], r'how are you': ["I'm doing fine. How about you?", "I'm doing well. Thank you."], r'synonym for (.*)': ['A synonym for {0} is {1}.'] }
我们可以通过调用match_rule()
函数,将用户输入的消息和规则进行匹配,然后返回一个随机选择的回复消息。
# 运行聊天机器人
while True:
message = input('> ')
response = match_rule(rules, message)
if response is not None:
print(response)
continue
# 尝试寻找同义词
words = nltk.word_tokenize(message.lower())
for i in range(len(words)):
synonyms = []
for syn in wordnet.synsets(words[i]):
for lemma in syn.lemmas():
synonyms.append(lemma.name())
if len(synonyms) > 1:
print("A synonym for", words[i], "is", synonyms[1])
break
当用户输入与规则或单词同义词匹配的消息时,机器人就会作出相应的回复。
以上是我的分享,欢迎大家来交流学习。