How do I check if a word ends with a certain string, from a file?

python, python-3.x

Solution

You have to split your lines into words and test each word:

a = sum(word.endswith('ly') for line in f for word in line.split())

This (ab)uses the fact that the Python boolean is a subclass of `int` and `True` == 1 and `False` == 0.

You can make it more explicit with a filter:

a = sum(1 for line in f for word in line.split() if word.endswith('ly'))

You may want to combine both counts into one loop however:

with open("unknown.txt", 'r') as f:
    total = lycount = 0
    for line in f:
        words = line.split()
        total += len(words)
        lycount += sum(1 for word in words if word.endswith('ly'))

try:
    percentage = (lycount / total) * 100
    print('{}% adverbs'.format(percentage))
except ZeroDivisionError:
    print('File is empty!')

Note that you should never use a blanket except statement; just catch the specific exception instead.

Problem

I already have this code: ``` f = open("unknown.txt", 'r') a = sum(line.count('ly').endswith() for line in f) words = 0 with open("unknown.txt", 'r') as f: words = len(f.read().split()) try: percentage = a/words*100 print('{}% adverbs'.format(percentage)) except: print('File is empty!') ``` But all this does is check if there is 'ly' in a word, how do I make it so only count as 'ly' if .endswith('ly') (i'm guessing those commands are going to be used, but i don't know how. Can someone please make my code do this? Thanks in advance!

Original source