这是我的代码段
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
请指出即使是最小的细节,我也非常感谢。
答案 0 :(得分:0)
如错误堆栈所述,在第13行中,您正在访问thesaurus
,就好像它是一个列表/字典(或任何可下标的对象)一样。由于thesaurus
是一个函数(不可下标),因此会出现错误。因此,您需要调用该函数(而不是访问它):
thesaurus(get_close_matches(words, definitions.keys()))
另外,您应该注意:
thesaurus
print(thesaurus(words))
函数
get_close_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))