在其他一些教程中,以下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
我不熟悉get_close_matches
。但根据文档:https://docs.python.org/2/library/difflib.html,它似乎需要一个列表(可迭代对象)。
data.keys()
返回一本字典。尝试先将其转换为列表。
elif len(get_close_matches(word, list(data.keys()))) > 0:
你的错误在这一行:
word = word.lower
.lower是一种方法,所以它应该是:
word = word.lower()
https://docs.python.org/3/library/stdtypes.html?highlight=lower#str.lower