【发布时间】:2019-02-20 01:46:56
【问题描述】:
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 实现中,有一个名为规则的列表,其中包含一组模式和相应的响应。如果模式匹配或输入的任何其他内容不在规则(最后一条规则)中,则此代码应该得到随机响应。
代码现在只输出,"Hi, there. Please state your problem" 用于所有输入语句。任何帮助为什么会发生这种情况??
如果你输入了一个在规则中匹配的句子,那么它会回复相应的响应。假设有如下规则:'(.*)are like(.*)', ["What resembelence do you see between {0} and {1}?"]] ,如果输入是 "Cats are like dogs" 响应应该类似于,什么你觉得猫和狗有相似之处吗?因此,它会从匹配中取出一组并放入相应的响应中。
【问题讨论】:
-
您能否就您期望的代码行为添加一些解释?
-
非常基本的问答行为。如果您在规则中输入了一个匹配的句子,那么它会回复相应的响应。假设如下规则: '(.*)are like(.*)', ["What resembelence do you see between {0} and {1}?"]] ,如果输入是“Cats are like dogs”回应应该是这样的,你觉得猫和狗之间有什么相似之处?因此,它从匹配中获取一组并放置在相应的响应中。
-
给新手的建议:如果一个答案解决了您的问题,请点击旁边的大复选标记 (✓) 接受它,也可以选择投票(投票至少需要 15 个声望)点)。如果您发现其他答案有帮助,请给他们投票。接受和投票有助于未来的读者。请看【相关帮助中心文章】[1] [1]:stackoverflow.com/help/someone-answers