Evolution of counting letters

Hello guys, yesterday I posted a program that counted the letters that appeared in a text. Today we will make something similar but instead of counting letters we will be counting words.

3m28eld_700wa_0

I will show you diferent ways of doing this, first using a build in function and then creating our own function.

word1

Here is the simplest way of doing it. We have a string stored in a variable (with split() we make the string into a list) and with the function counter() that does exactly what we want, we print the result. It looks like this:

word2

Ok now a little more complicated (we should not do complicated stuff, this is just for learning purposes)

word3

In this one we check if the word in the list (that is formed with spit()) is in a list, if it is not, the word is added and in thesame position in other list it is added a value 1 to the amount of times it repeats. If the word is already on the list we recover the index of that word and on the same position we add +1 to the list with numbers. Finally we print the word followed by it’s frecuency:

word4

pm0zodl_700wa_0

Now  we build our own function

The first funtion filtrar erases all the invalid characters so the only thing left are lower case words.word5The function count_words() does the same as what we previously explained with the lists but instead of using 2 lists, it adds the word to a dictionary with the value of the amount of times it repeats itself, pretty easy right?

We proceed to ask the user for an input or to open a text file, when opening the text file we type ‘r’ for it to be in read mode (not modified), we change the file to lower case (without modifying the original file), we filter it and then use our count_words function. This is the output:

word6

ymkparr_700wa_0

That’s all for this post. Take care and enjoy this video:

Follow me on twitter @danigguemez

The code is avaliable in github: https://github.com/Guemez/TC1014/blob/master/countwords.py

#TC101 #python #DailyChallenge #files

Leave a comment