我正在创建一个聊机器人,它使用CSV文件中的问题,并使用SKlearn和NLTK检查相似性。然而,如果相同的输入被输入两次,我会遇到一个错误:
这是主要代码,它接收用户输入并向用户输出答案:
import pandas as pddata=pd.read_csv('FootballQA.csv')question=data['Q'].tolist()answer=data['A'].tolist()lemmer = nltk.stem.WordNetLemmatizer()#WordNet是NLTK中包含的英语语义导向词典def LemTokens(tokens): return [lemmer.lemmatize(token) for token in tokens]remove_punct_dict = dict((ord(punct), None) for punct in string.punctuation)def LemNormalize(text): return LemTokens(nltk.word_tokenize(text.lower().translate(remove_punct_dict)))GREETING_INPUTS = ("hello", "hi", "greetings", "sup", "what's up","hey","how are you")GREETING_RESPONSES = ["hi", "hey", "hi there", "hello", "I am glad! You are talking to me"]def greeting(sentence): for word in sentence.split(): if word.lower() in GREETING_INPUTS: return random.choice(GREETING_RESPONSES)GI = ("how are you")GR = ["i'm fine","good,how can i help you!"]def greet(sentence): for word in sentence.split(): if word.lower() in GREETING_INPUTS: return random.choice(GREETING_RESPONSES) def responses(user): response='' question.append(user) TfidfVec = TfidfVectorizer(tokenizer=LemNormalize, stop_words='english') tfidf = TfidfVec.fit_transform(question) val = cosine_similarity(tfidf[-1], tfidf) id1=val.argsort()[0][-2] flat = val.flatten() flat.sort() req = flat[-2] if(req==0): robo_response=response+"I am sorry! I don't understand you" return robo_response else: response = response+answer[id1] question.remove(user) return response command=1 while(command): v = input("Enter your value: ") if(v=="exit"): command=0 else: print(responses(str(v)))
当程序运行时,它会要求用户输入值,但如果相同的输入被输入两次就会出现问题。如果我输入”football”,它会第一次正确显示我想要的输出,但第二次输入时会停止程序并显示以下错误:
Enter your value: scoredAlan shearer holds the goal record in the premier league.Enter your value: footballI am sorry! I don't understand youEnter your value: footballTraceback (most recent call last): File "C:\Users\Chris\Desktop\chatbot_simple\run.py", line 79, in <module> print(responses(str(v))) File "C:\Users\Chris\Desktop\chatbot_simple\run.py", line 68, in responses response = response+answer[id1]IndexError: list index out of range
CSV文件内容如下:
Q,AWho has scored the most goals in the premier league?,Alan shearer holds the goal record in the premier league.Who has the most appearences in the premier league?,Gareth Barry has the most appearences in premier league history.
我尝试在每次输入后删除变量,但它似乎仍然记得之前的输入,有人有任何建议吗?谢谢Chris
回答:
answer=data['A'].tolist()
然后稍后
id1=val.argsort()[0][-2]response = response+answer[id1]
所以如果answer
中没有id1
,你会得到索引超出范围的错误。所以在你的情况下,len(answer) >= id1
是true
的。