import random
import re
rules=[["(.*)hello(.*)",["Hi there. Please state your problem"]],
["(.*)name(.*)",["Great, good to know","I am not interested
in names"]],
["(.*)sorry(.*)",["please don't apologize","Apologies are not necessary","What feelings you have when you apologize?"]],
["(.*)",["Very interesting","I am not sure I understand you fully","Please continue",
"Do you feel strongly about discussing such things?","\\2"]]]
grammar = {
"am": "are",
"was": "were",
"i": "you",
"i'd": "you would",
"i've": "you have",
"i'll": "you will",
"my": "your",
"are": "am",
"you've": "I have",
"you'll": "I will",
"your": "my",
"yours": "mine",
"you": "me",
"me": "you"
}
def correction(word):
character=word.lower().split()
for i, j in enumerate(character):
if j in grammar:
character[i]=grammar[j]
return " ".join(character)
def test(sentence):
for pattern, message in rules:
match=re.match(pattern,sentence.rstrip(".!"))
if match:
response = random.choice(message)
temp = " " + correction(match.group())
response2 = re.sub(r"\\2",temp,response)
return response2
else:
recall=random.choice(message)
return recall
while True:
sentence =input("You: ")
print("JBot: " + test(sentence))
if sentence == "quit":
break
在这个简单的eliza
实现中,有一个名为rule的列表,其中包含一组模式和相应的响应。如果模式匹配或输入了任何不在规则(最后一条规则)中的内容,则该代码应该获得随机响应。你知道吗
代码现在只输出所有输入语句的"Hi, there. Please state your problem"
。为什么会这样??你知道吗
如果您输入了规则中匹配的句子,那么它将以相应的响应进行回复。假设一个规则如下:'(.*)
就像(.*)'
,[“你在{0}
和{1}
之间看到了什么储备?”]],如果输入是"Cats are like dogs"
,那么响应应该是这样的,你看到猫和狗之间有什么相似之处?因此,它需要从比赛中选出一组人,并在各自的回答中给出位置。你知道吗
我已经修复了您的代码,现在应该可以正常工作了:
备注:
test
函数的循环中的else
将在每次迭代时退出循环,因此您将无法浏览所有规则、语法。我把它放在for
之后,这将强制首先检查每个规则,然后再选择默认的随机选择答案。你知道吗代码:
输出:
相关问题 更多 >
编程相关推荐