[英]Why do I get the error "'function' object is not subscriptable'
This is my code block 这是我的代码块
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))
I expected to receive the meaning of the word "Grief". 我希望收到“悲伤”一词的含义。 However, I kept receiving the error : function object is not subscriptable. 但是,我一直收到错误消息:函数对象不可下标。
Here is the terminal log, just in case it might help: 这是终端日志,以防万一它可能会有所帮助:
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
Please point out even the smallest details, I would appreciate that very much. 请指出即使是最小的细节,我也非常感谢。
As stated by the error stack, in line 13 you are accessing thesaurus
as if it was a list/dictionary (or any subscriptable object). 如错误堆栈所述,在第13行中,您正在访问thesaurus
,就好像它是一个列表/词典(或任何可下标的对象)一样。 Since thesaurus
is a function (which is not subscriptable), you get an error. 由于thesaurus
是一个函数(不可下标),因此会出现错误。 Thus, you need to invoke the function (instead of accessing it): 因此,您需要调用该函数(而不是访问它):
thesaurus(get_close_matches(words, definitions.keys()))
Also, you should notice: 另外,您应注意:
thesaurus
function by calling print(thesaurus(words))
在代码末尾,您可以通过调用print(thesaurus(words))
正确地调用thesaurus
功能。 get_close_matches
to avoid multiple calls to the same function (which can lead to performance degradation if the call is resource consuming). 考虑重新使用get_close_matches
的结果,以避免对同一函数的多次调用(如果该调用消耗资源,则可能导致性能下降)。 I suggest you the following solution: 我建议您以下解决方案:
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.