2021年5月2日星期日

How do you count the number of words in a column while ignoring blank lines

I have the following list in a text file:

banana

egg

balloon

green giant

How do I create a dictionary that counts the words, ignoring the blank lines

my code so far:

def make_dictionary(filename):      text = open(filename,'r').read()      wordfreq = {}      for word in text.strip().split('\n'):          wordfreq[word] = wordfreq.get(word, 0) +1  return wordfreq  

This will return the counts I need, except it gives me a count for the blank lines as '':7, which I don't need. I cant just split with () because of the double word green giant. Hence I have to split with '\n'

https://stackoverflow.com/questions/67362992/how-do-you-count-the-number-of-words-in-a-column-while-ignoring-blank-lines May 03, 2021 at 10:56AM

没有评论:

发表评论