如何避免python中的非类型错误

如何避免python中的非类型错误,python,python-3.x,Python,Python 3.x,我创建了以下函数: def rRWords(filename): infile = open(filename, "r") lines = infile.readlines() result = [] for xx in lines: xx.lower result.append(xx.split(' ')[3]) result.sort dic = {} for line in result: words = line.split() words

我创建了以下函数:

def rRWords(filename):
infile = open(filename, "r")
lines = infile.readlines()
result = []
for xx in lines:
      xx.lower
      result.append(xx.split(' ')[3])
result.sort
dic = {}
for line in result:
      words = line.split()
      words = line.rsplit()
      for word in words :
            if word not in dic:
                  dic[word] = 1
dic2 = {}
for item in dic.items():
      if(item[0] == getWord(item[0])):
         #print(item[0])
         dic2[item[0]] = 1
infile.close()
filter(None, dic2)
print(len(dic2))
#print(*sorted(map(str.lower, dic2)), sep='\n')
#return
当我对一个包含10个单词的小文件使用这个函数时,它就工作了

然而,当我运行检查函数时,它使用了一个大约80000字的大文本文件,我得到了一个错误。检查功能如下所示:

wordset = rRWords("master.txt")
if len(wordset) == 80000 and type(wordset) is set:
    print("Well done Lucy Success!")
else:
    print("Not good Lucy Failed")    
当我运行此程序时,它会将整个文本文件打印到屏幕上(我不希望这样),最后我得到:

Traceback (most recent call last):
File "C:\Users\jemma\Documents\checkscript.py", line 19, in <module>
if len(wordset) == 80000 and type(wordset) is set:
TypeError: object of type 'NoneType' has no len()
希望我对这个问题的编辑能让这更清楚

提前感谢,,
Jemma

您可以通过对
wordset
执行布尔运算来检测它是否不是
None

>>> wordset = None
>>> if wordset:
...     print('not None')
... else:
...     print('might be None, or an empty sequence')
might be None, or an empty sequence
所以你可以用这个:

if wordset and len(wordset) == 700 and type(wordset) is set:
   ...
如果
wordset
None
且不会继续进行任何其他比较(称为短路),则比较将失败


看(答案是肯定的)

wordset
不是你想象的那样。您可以在某个时候将其设置为
None
。找出原因。通过if语句的后半部分判断,您正在检查它是否实际上是一个
,这应该是if语句的第一部分,然后检查它是否是一个
if wordset and len(wordset) == 700 and type(wordset) is set:
   ...