Read text from text file

Question:

My text file has 2-3 paragraphs with blank line seperating each para. I have to read all words from the text file and count the words. But the problem is it is reading the blank line and give result as ‘ :2’. How to remove this line while reading the file. I already used line = line.strip() , but still shows ‘ :2’
output shows:

the : 2

: 2

are : 1

text file contents are:

Google makes money by advertising. People or companies who want people to buy their product, service, or ideas give Google money, and Google shows an advertisement to people Google thinks will click on the advertisement.

Google only gets money when people click on the link, so it tries to know as much about people as possible to only show the advertisement to the right people.

This is the last line.

d=dict()
f = open('/Users/admin/Desktop/textfile.txt','r')
for line in f:
    line = line.strip()
    line=line.strip('n')
    words = line.split(" ")
                     
    for word in words:
        if word in d:
            d[word] = d[word] + 1
        else:
            d[word] = 1

for key in list(d.keys()):
    print(key, ":", d[key])
Asked By: Ayesha

||

Answers:

Check empty lines before you count words in it

for line in f:
    line = line.strip()
    if line: 
       # it is not empty, so continue counting

Also, you can use a Counter rather than a plain dict

from collections import Counter 

d = Counter()
with open(...) as f:
    for line in f:
        line = line.strip()
        if line:
            words = line.split()
            d.update(Counter(words))

for key, value in d.items():
    print(f'{key}: {value}')
Answered By: OneCricketeer
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.