2

The question:

A- Write a function called has_no_e that returns True if the given word doesn’t have the letter “e” in it.

B- Modify your previous program to print only the words that have no “e” and compute the percentage of the words in the list have no “e.”

def main():
    file = input("Enter a file: ")
    file_output = open(file, 'r')
    output = (file_output.read())
    for line in output:
        word = line.strip()
        if len(word)>20:
            print (word)
    no_e = has_no_e(word)

    count = 0
    for line in output:
        word = line.strip()
        if has_no_e(word):
            count +=1
            print (word)
    percent = (count/1)*100 #Im still working on the percentage part
    print (percent)

def has_no_e(word):
    for char in word:
        if char in 'Ee':
            return False
        return True

Output:

c

h

s

i

s

c

o

o

l

900.0

Problem: So my problem is that instead of printing out the entire word, its printing out every letter (except e). I'm trying to get it to print it out the entire word if it doesn't have the letter e. For example, my file said "cheese is cool". I was expecting it to output "is cool" only. How would I go about doing this? Also, for the percentage: How can I bunch the word as one instead of individual letters? This way for the percentage I could do (count/# words) *100.

Jane
  • 41
  • 2
  • 7

1 Answers1

0

file_output.read() reads the entire file and returns it as a string. So output is the string "cheese is good".

The issue is for line in string:. You expect it to have line="cheese", then line="is", and finally line="good".

However, it instead goes character by character. So it runs the loops with line='c', then with line='h' and so on. For it to perform as you expect, you need to split output on either newlines or spaces (depending how your file separates words) and iterate through the resulting list.

fuzzything44
  • 701
  • 4
  • 15