简体   繁体   中英

Check for letter in text file python

I need to count the number of vowels in a text file given to me (with python program) and return the number. For whatever reason when I run the program the file returns 0 vowels even though the count variable is supposed to increase by one each time it loops and finds a vowel.

def numVowels(file):
    count = 0
    opened_file = open(file)
    content = opened_file.readlines()
    for char in content:
        if char.lower() in 'aeiou':
            count += 1
    return(count)

I'm not sure if that is because I am working with a text file, but usually I am able to do this without an issue. Any help is greatly appreciated.

Thank you!

readlines() returns a list of lines from the file so for char in content: means char is a line of text in the file which isn't what you are looking for.
You can read() the whole file into memory or iterate through the file line by line and then iterate through the line character at at time:

def numVowels(file):
    count = 0
    with open(file) as opened_file:
        for content in opened_file:
            for char in content:
                if char.lower() in 'aeiou':
                    count += 1
    return count

You can sum a generator of 1's to produce the same value:

def numVowels(file):
    with open(file) as f:
        return sum(1 for content in f for char in content if char.lower() in 'aeiou')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM