这是我的代码块
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))我希望能得到“悲伤”这个词的意思。但是,我一直收到错误: function不可订阅。
这是终端日志,以防有帮助:
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请指出,即使是最小的细节,我将非常感谢。
发布于 2018-08-02 11:32:16
正如错误堆栈所述,在第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))https://stackoverflow.com/questions/51652471
复制相似问题