如何绕过python

时间:2017-02-04 23:53:08

标签: 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 = 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()

我只想让这个检查功能运行并输出:

Well done Lucy Success!

希望我对这个问题的编辑能让我更清楚。

提前致谢, 杰马

1 个答案:

答案 0 :(得分:2)

您可以通过执行布尔操作来检测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:
   ...

如果wordsetNone,则比较将失败,并且不会继续进行任何其他比较(称为短路)。

Does Python support short-circuiting?(答案是肯定的)