首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么我得到错误“‘函数’对象是不可订阅的‘

为什么我得到错误“‘函数’对象是不可订阅的‘
EN

Stack Overflow用户
提问于 2018-08-02 11:26:47
回答 1查看 3.7K关注 0票数 0

这是我的代码块

代码语言:javascript
复制
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不可订阅。

这是终端日志,以防有帮助:

代码语言:javascript
复制
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

请指出,即使是最小的细节,我将非常感谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-08-02 11:32:16

正如错误堆栈所述,在第13行中,您正在访问thesaurus,就好像它是一个列表/字典(或任何可订阅对象)一样。因为thesaurus是一个函数(它不是可订阅的),所以您将得到一个错误。因此,您需要调用该函数(而不是访问它):

代码语言:javascript
复制
thesaurus(get_close_matches(words, definitions.keys()))

此外,你应该注意到:

  • 在代码的末尾,您将通过调用thesaurus函数正确地调用print(thesaurus(words))函数。
  • 考虑重用get_close_matches的结果,以避免对同一个函数进行多次调用(如果调用占用资源,则会导致性能下降)。

我建议您采取以下解决方案:

代码语言:javascript
复制
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))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51652471

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档