【问题标题】:error:'builtin_function_or_method' object is not iterable错误:'builtin_function_or_method' 对象不可迭代
【发布时间】:2019-01-12 17:24:10
【问题描述】:

在其他一些教程中,以下 python 代码用于从适用于它们的 json 文件中查找单词。但是,不适合我。 你能帮我摆脱这个错误吗?

import json
from difflib import get_close_matches

data = json.load(open("data.json"))

def translate(word):
    word = word.lower
    if word in data:
        return data[word]
    elif len(get_close_matches(word, data.keys())) > 0:
        yn=input ("did you mean %s instead? Enter Y if yes and N if no" % get_close_matches(word, data.keys())[0])
        if yn == "Y":
            return data[get_close_matches(word, data.keys())[0]]
        elif yn == "N":
            return("the word doesn't exist")
        else:
            print("we don't understand your entry")
    else:
        return("the word does't exist please crosscheck it")

word = input("enter a word: ")

output = translate(word)

if type(output) == list:
    for item in output:
        print(item)
else:
    print(output)

这是我得到的错误:

Traceback (most recent call last):
  File "pracjson.py", line 23, in <module>

    output = translate(word)
  File "pracjson.py", line 10, in translate
    elif len(get_close_matches(word, data.keys())) > 0:
  File "C:\Users\Vishnu's World\AppData\Local\Programs\Python\Python37\lib\difflib.py", line 723, in get_close_matches
    s.set_seq2(word)
  File "C:\Users\Vishnu's World\AppData\Local\Programs\Python\Python37\lib\difflib.py", line 279, in set_seq2
    self.__chain_b()
  File "C:\Users\Vishnu's World\AppData\Local\Programs\Python\Python37\lib\difflib.py", line 311, in __chain_b
    for i, elt in enumerate(b):
TypeError: 'builtin_function_or_method' object is not iterable

【问题讨论】:

    标签: python-3.x function built-in iterable traceback


    【解决方案1】:

    我不熟悉get_close_matches。但根据文档:https://docs.python.org/2/library/difflib.html,它似乎需要一个列表(可迭代对象)。

    data.keys() 返回一个字典。尝试先将其转换为列表。

        elif len(get_close_matches(word, list(data.keys()))) > 0:
    

    【讨论】:

      【解决方案2】:

      你的错误在这一行:

      word = word.lower
      

      .lower 是一个方法,所以应该是:

      word = word.lower()
      

      https://docs.python.org/3/library/stdtypes.html?highlight=lower#str.lower

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-07-20
        • 1970-01-01
        • 2022-12-05
        • 2011-12-13
        • 2016-09-11
        • 1970-01-01
        • 2020-03-26
        相关资源
        最近更新 更多