I am currently teaching myself python and I came across this task: I have to extract the content of a .txt file and make a counter for every word inside. I already tried different methods, but I always get an error, which I can´t explain to myself. The error right now looks like this:
for key in dic: TypeError: 'NoneType' object is not iterable
I don´t know why I get this error, because in another task, I was able to iterate through a dictonary.
My current attempt looks like this:
file = open("file.txt", "w")
file.write("English texts for beginners to practice reading and comprehension online and for free. Practicing your comprehension of written English will both improve your vocabulary and understanding of grammar and word order. The texts below are designed to help you develop while giving you an instant evaluation of your progress.")
file.close()
file = open("file.txt", "r")
List = file.read().split()
file.close
#If the word from the list is already in the dictonary, the programm shall check for the next word in List. If it is not in the dictonary it shall add it to the dictonary
def WordAdd(List):
dic = {}
for word in List:
for key in dic:
if word == key:
break
else:
dic[word] = 0
return dic
#counts the words inside the List
def Wordcount(L, dic):
for x in L:
dic[x] =1
#Output of the elemts in the dictonary with its values
def Output(dic):
for key in dic:
print(key ": ", key.get(key))
Output(Wordcount(List, WordAdd(List)))
´´´
CodePudding user response:
Let me give you some advices. Let's try to undertand the error first:
for key in dic: TypeError: 'NoneType' object is not iterable
This syntax generally expects that right side (dic
in this case) is iterable (you will meet it many times while learning python). You can think of it as structure that you can get elements from (e.g lists or dicts). But here you get NoneType
, so your your dic is None
. Where your dic comes from? It's what Wordcount returns!
def f():
pass
# it's explicitly returns None, the same as writing return None
We got first problem,
def Wordcount(L, dic):
for x in L:
dic[x] =1
# we need to return our dic here
return dic
Oh no! There is another error, what now?
print(key ": ", key.get(key))
AttributeError: 'str' object has no attribute 'get'
So now it says us that we try to access get
attribute of type str
. It thinks our key
is string, why?
for key in dic:
print(key ": ", key.get(key))
Indeed, key
is just a key of our dict, so you probably meant dic.get(key)
Now it works! Some unrelated stuff that can help you with your python adventure
For interacting with file you should use context, so instead of:
file = open("file.txt", "w")
file.write("...")
file.close()
Use
with open("file.txt", "w") as file:
file.write("...")
It will close a file for you and it protects you with forgetting about it or making a programming mistake (look, you wrote file.close
instead of file.close()
) or even program crush.
Second thing pointed in comment
for word in List:
for key in dic:
if word == key:
# should be
for word in List:
if key in dic:
And as higher level hint, there is something like defaultdict
in python, which set the default value if key does not exist, look
from collections import defaultdict
dic = defaultdict(int)
print(dic["a"]) # 0
dic["c"] = 1 # it works, dic["c"] does not exist so default value 0 is taken
print(d["c"]) # 1
CodePudding user response:
You could use this code:
count = 0
file = open("file.txt", "r")
read_data = file.read()
words = set(read_data.split())
for word in words:
count = 1
print('Total Unique Words:', count)