TypeError:“ NoneType”类型的参数不可迭代,我无法理解问题

时间:2019-07-23 20:40:27

标签: python typeerror

我是编程的初学者,我正在制作一个使用输入文本并对其进行自动更正的程序。该代码对于小句子似乎很好,但是当我粘贴一个段落时。代码返回此错误。

# this a program that accepts input from the user and returns
#the number of words and the auto-correct the use

# step1: taking input from user (string) 
docx = input('enter the letter')

#step2: extract words from sentence
str_list = docx.split()
str_list = [x.lower() for x in str_list]

#step3: autocorrect part

# loading json file
import json
data = json.load(open('C:/Users/OMAIR salah/Desktop/autocorrect/words_dictionary2.json'))

# importing the comparing library
from difflib import get_close_matches

# the loop ( change the words if the spelling is wrong)
for i in range(0,len(str_list)):
    searcher = data.get(str_list[i][0])
    if str_list[i] in searcher :
        pass
    else:
        if len(get_close_matches(str_list[i],data.values())) > 0 :
            str_list[i] = get_close_matches(str_list[i],data.values()[0]
        else:
            print(f'the word {str_list[i]} does not exist')

1 个答案:

答案 0 :(得分:0)

问题出在此代码中:

# the loop ( change the words if the spelling is wrong)
for i in range(0,len(str_list)):
    searcher = data.get(str_list[i][0])
    if str_list[i] in searcher :

找不到请求的密钥时,.get()方法将返回None。因此,在这种情况下,searcherNone。然后,您尝试使用in运算符,该运算符通过迭代来完成其工作,但是您无法遍历None,因此会出错。

一种可能的解决方法是在找不到请求的密钥时,为.get()提供一个额外的参数,以指定应返回的默认值,而不是None

# assign an empty list to searcher if the key is not found
searcher = data.get(str_list[i][0], [])