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