Python报错‘builtin_function_or_method’不可下标,求解决方法
解决对话机器人的'builtin_function_or_method' object is not subscriptable错误
错误原因分析
这个错误表示你试图对一个内置函数/方法使用下标(如[]),但只有列表、字典、字符串这类序列类型才能用下标访问。虽然报错行在print(response(user_response)),但问题根源通常分为两种情况:
response被误赋值为内置函数/方法,而非你定义的回复生成函数;response函数内部存在下标误用(把函数/方法当成序列类型访问)。
具体修复步骤
1. 确认response是正确定义的函数
检查代码中是否把response赋值成了内置对象,比如:
# 错误示例:把response赋值成了内置list函数 response = list
如果有这类代码,删除后确保response是你自定义的函数,比如:
def response(user_text): # 这里写你的回复生成逻辑 # 比如基于NLTK的相似度匹配、关键词回复等 return "对应的回复内容"
2. 检查response函数内部的代码
如果response是正确定义的函数,错误大概率出在函数内部。常见的误用场景:
- 把函数调用写成了下标访问,比如误写
nltk.synsets[word](正确应为nltk.synsets(word)); - 用字符串作为列表索引,比如
sent_tokens[user_response](user_response是用户输入的字符串,需换成数字索引)。
以下是一个正确的response函数示例(基于TF-IDF相似度匹配,避免下标错误):
from sklearn.metrics.pairwise import cosine_similarity from sklearn.feature_extraction.text import TfidfVectorizer def response(user_response): temp_tokens = sent_tokens + [user_response] tfidf = TfidfVectorizer() tfidf_matrix = tfidf.fit_transform(temp_tokens) # 计算用户输入与历史语句的相似度 vals = cosine_similarity(tfidf_matrix[-1], tfidf_matrix[:-1]) idx = vals.argsort()[0][-1] flat = vals.flatten() flat.sort() req_tfidf = flat[-1] if req_tfidf == 0: return "I am sorry! I don't understand you" else: return sent_tokens[idx]
3. 修复其他小问题
代码中还有一处语法错误:flag = false应改为flag = False(Python布尔值首字母大写),否则会触发NameError。
内容的提问来源于stack exchange,提问作者Aakash Tiwari
相关产品推荐
相关产品推荐

