WSQ12 Word count

This code is not really hard. It’s about asking the user for a word and count how many times does it appear in a .txt file.

Let’s start.

I’ll explain the code that Ken helped me with and then I’ll explain my code.

To count words in a text file you need to consider several things:

The word might have lower and upper case letters on it, or it could be next to other word without any space, so the “split” function won’t help a lot.

So here’s Ken’s code:

wsq1202

As you can see, our big_string has the word “bananas”, but not al the “bananas” have the same structure. So first of all. we shall convert every word to lowercase (line 3).

To give more flexibility to the program, we convert the letters of BaNana to lowercase.

Then, python has this beautiful function that will find the word that we’re looking for (line 7).

After that, what we’ll do is look for the word checking each character, and while the string is not empty, the program will check it and find all the bananas. Kind of funny, right? loved this exercise.

Aaaaand here we go. Here’s my code:

wsq1203

Check that I added an input to catch the wanted word. Also, as my file has several lines, it’s obvious that I need to evaluate them all. That’s why I inserted the “for” loop (line 5)

That’s all for today, fellows. Have a nice day.

Anuncios