Home > OS >  How to loop through words with conditions
How to loop through words with conditions

Time:03-26

Your task is to write a program that loops through the words in the provided jane_eyre.txt file and counts those words which fulfill both of the following conditions:

The word has more than 10 characters The word does not contain the letter "e" Once you've finished the aggregation, let your program print out the following message: There are 10 long words without an 'e'.

My work:

count = 0

f = open("jane_eyre.txt").read()

words = f.split()

if len(words) > 10 and "e" not in words:

   count  = 1

print("There are", count, "long words without an 'e'.")

The count result is 1 but it should be 10. What's wrong with my work??

CodePudding user response:

You have to iterate on each word, with best practice:

with open('jane_eyre.txt') as fp:  # use a context manager
    count = 0  # initialize counter to 0
    for word in fp.read().split():  # for each word
        if len(word) > 10 and not 'e' in word:  # your condition
            count  = 1  # increment counter
    print(f"There are {count} long words without an 'e'.")  # use f-strings

But pay attention to punctuation: "imaginary," is 10 characters length but the word itself has only 9 characters.

CodePudding user response:

You need to loop through each word. So something like:

count = 0

f = open("jane_eyre.txt").read()

words = f.split()

for word in words:
    if len(word) > 10 and "e" not in word:
    
       count  = 1

print("There are", count, "long words without an 'e'.")
  • Related