-5

I have created the following function:

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

When I use the function against a small file containing say 10 words it works.

However when I run the checking function against this which uses a big text file with about 80000 words I get an error. The checkfunction is as below:

wordset = rRWords("master.txt")
if len(wordset) == 80000 and type(wordset) is set:
    print("Well done Lucy Success!")
else:
    print("Not good Lucy Failed")    

When I run this it prints to the whole text file to the screen (which I do not want) and at the end I get:

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()

I just want this check function to run and output:

Well done Lucy Success!

Hope my edit to this question makes this clearer.

Thanks in advance, Jemma

NoobyD
  • 121
  • 7
  • 4
    `wordset` isn't what you think it is. You set it to `None` at some point. Figure out why. – user2357112 Feb 04 '17 at 23:55
  • Judging by by the 2nd half of the if statement you are checking if it is actually a `set`, this should be the first part of the if statement, then checks the length if it is a `set` – Steven Summers Feb 05 '17 at 02:14

1 Answers1

2

You can detect if wordset is not None by performing a boolean operation with it:

>>> wordset = None
>>> if wordset:
...     print('not None')
... else:
...     print('might be None, or an empty sequence')
might be None, or an empty sequence

So you can use this:

if wordset and len(wordset) == 700 and type(wordset) is set:
   ...

The comparison will fail if wordset is None and won't continue to do any of the other comparisons (called short-circuiting.)

See Does Python support short-circuiting? (the answer's yes)

Community
  • 1
  • 1
Peter Wood
  • 23,859
  • 5
  • 60
  • 99