我正在尝试制作一个聊天机器人,我的主要问题是在程序找出最合适的后,我无法找到输出特定响应的方法。
我最初的想法是这样的:
检查用户输入的单词,并将其与预先做出的响应进行比较。 这些单词分为 2 类:requiredWords(如果用户输入中不存在所有单词,则响应将被自动忽略)和 possibleWords(可能出现在用户响应中但并非全部都存在) 到场。
这是我编写的代码:
import random
import time
import re
responses = []
possibleWords = []
requiredWords = []
recognisedResponse = True
fw = 0 #fownd words
rw = 0 #required words
nw = 0 #needed words
pw = 0 #possible words
userInput = input('You: ')
converted = re.split(r'\s+|[,;?!.-]\s*', userInput.lower())
def checkingInput():
for word in converted:
if word in possibleWords:
fw = fw +1
else:
fw = fw
for word in converted:
if word in requiredWords:
rw = rw +1
else:
rw = rw
RwCalc = int(rw / nw)*100
PwCalc = int(fw / pw)*100
if RwCalc == 100:
recognisedResponse = True
responses.append(PwCalc)
else:
recognisedResponse = False
def howAreYou():
possibleWords = ['how','are','you']
requiredWords = ['how','you']
nw = 2
pw = 3
checkingInput()
print('Bot: I\'m good, thanks for asking!')
time.sleep(1)
print('Bot: How are you?')
def makeAcake():
possibleWords = ['how','do','you','make','a','cake']
requiredWords = ['how','you']
nw = 2
pw = 6
checkingInput()
print('Bot: I have no idea!')
time.sleep(1)
print('Bot: Maybe ask Google instead?')
output = max(responses)
if recognisedResponse == False:
time.sleep(1)
print('Bot: I\'m sorry, I don\'t understand.')
time.sleep(1)
print('Bot: Could you re-phrase that?')
else:
print(output)
因为我还不知道如何将响应链接到整数,所以当前只应该输出整数,但是我收到此错误:
line 61, in <module>
output = max(responses)
ValueError: max() arg is an empty sequence
当我第一次运行它时,我只做了一个响应,所以我做了第二个响应(makeAcake),它使用与第一个响应相同的所需单词来查看这是否是问题所在,但它仍然返回同样的错误。
定义了一些函数,但它们永远不会被调用。
这行代码:
output = max(responses)
不在函数内部,因此它立即运行,当然 responses
此时仍然是一个空列表,因为没有调用任何函数,因此您会收到错误。您是否希望该代码成为函数的一部分?