Python 为什么我会得到这个错误';功能';对象不可下标';
这是我的代码块Python 为什么我会得到这个错误';功能';对象不可下标';,python,Python,这是我的代码块 import json import difflib from difflib import get_close_matches definitions = json.load(open("data.json")) def thesaurus(words): if words in definitions: return definitions[words] elif len(get_close_matches(words, definitio
import json
import difflib
from difflib import get_close_matches
definitions = json.load(open("data.json"))
def thesaurus(words):
if words in definitions:
return definitions[words]
elif len(get_close_matches(words, definitions.keys())) > 0:
yn = input("Did you mean %s instead? Enter 'Y' if yes or 'N' if no: " % get_close_matches(words,definitions.keys()) [0])
if yn == "Y":
return thesaurus[get_close_matches(words, definitions.keys())]
elif yn == "N":
return "None found"
else:
return "Please check word again"
words = input("Look Up: ").lower()
print(thesaurus(words))
我希望得到“悲伤”这个词的含义。但是,我一直收到错误:函数对象不可下标
这是终端日志,以防万一可能会有所帮助:
My-MacBook-Pro:Python Adwok$ python3 dictionary.py
Look Up: GRERFAG
Did you mean grief instead? Enter 'Y' if yes or 'N' if no: Y
Traceback (most recent call last):
File "dictionary.py", line 22, in <module>
print(thesaurus(words))
File "dictionary.py", line 13, in thesaurus
return thesaurus[get_close_matches(words, definitions.keys())]
TypeError: 'function' object is not subscriptable
My MacBook Pro:Python Adwok$python3 dictionary.py
查找:GRERFAG
你是说悲伤吗?如果是,请输入“Y”;如果否,请输入“N”:Y
回溯(最近一次呼叫最后一次):
文件“dictionary.py”,第22行,在
印刷(同义词表(单词))
同义词库第13行的“dictionary.py”文件
返回同义词库[get_close_matches(单词,定义.keys())]
TypeError:“函数”对象不可下标
请指出哪怕是最细微的细节,我将非常感激 如错误堆栈所述,在第13行中,您正在访问
同义词库
,就好像它是一个列表/词典(或任何可订阅对象)。由于同义词库
是一个函数(不可下标),因此会出现一个错误。因此,您需要调用函数(而不是访问它):
此外,您还应注意:
- 在代码末尾,通过调用
print(同义词库(单词))
- 考虑重用
的结果,以避免对同一函数进行多次调用(如果调用占用资源,则可能导致性能下降)李>get\u close\u matches
import json
import difflib
from difflib import get_close_matches
definitions = json.load(open("data.json"))
def thesaurus(words):
if words in definitions:
return definitions[words]
else:
close_matches = get_close_matches(words, definitions.keys())
if len(close_matches) > 0:
yn = input("Did you mean %s instead? Enter 'Y' if yes or 'N' if no: " % get_close_matches(words,definitions.keys()) [0])
if yn == "Y":
return thesaurus(close_matches)
elif yn == "N":
return "None found"
else:
return "Please check word again"
words = input("Look Up: ").lower()
print(thesaurus(words))
因为您正在订阅函数对象。
import json
import difflib
from difflib import get_close_matches
definitions = json.load(open("data.json"))
def thesaurus(words):
if words in definitions:
return definitions[words]
else:
close_matches = get_close_matches(words, definitions.keys())
if len(close_matches) > 0:
yn = input("Did you mean %s instead? Enter 'Y' if yes or 'N' if no: " % get_close_matches(words,definitions.keys()) [0])
if yn == "Y":
return thesaurus(close_matches)
elif yn == "N":
return "None found"
else:
return "Please check word again"
words = input("Look Up: ").lower()
print(thesaurus(words))