“IndexError: 列表索引超出范围” 当创建自动响应机器人时

我正在创建一个聊机器人,它使用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) >= id1true的。

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注