-5
にNoneTypeエラーを回避することができ、私は次の関数を作成しました:はどのように私はPythonの
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語の大きなテキストファイルを使用しているチェック機能を実行すると、エラーが発生します。 checkfunctionは以下の通りである:私はこれを実行すると
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!
は、この質問に対する私の編集は、これが明確になります願っています。
>>> 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」に設定します。理由を理解してください。 – user2357112
if文の後半部で判断すると、実際に 'set'かどうかをチェックしています。これはif文の最初の部分でなければなりません。 –