How to count the number of words in a sentence, ignoring numbers, punctuation and whitespace?

str.split() without any arguments splits on runs of whitespace characters: >>> s=”I am having a very nice day.” >>> >>> len(s.split()) 7 From the linked documentation: If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain … Read more

How can I loop through blocks of lines in a file?

Here’s another way, using itertools.groupby. The function groupy iterates through lines of the file and calls isa_group_separator(line) for each line. isa_group_separator returns either True or False (called the key), and itertools.groupby then groups all the consecutive lines that yielded the same True or False result. This is a very convenient way to collect lines into … Read more