“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

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

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