[英]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. 我需要计算给我的文本文件中的元音数量(使用python程序)并返回该数量。 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.
不管出于什么原因,即使我每次运行该程序并找到一个元音时count变量都应该增加一个,该文件仍会返回0个元音。
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. readlines()
返回文件中的行列表,因此for char in content:
意味着char
是文件中不是您要查找的文本行。
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: 您可以将整个文件
read()
到内存中,或者逐行遍历文件,然后一次遍历行字符:
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: 您可以将一个1的生成器求和以产生相同的值:
def numVowels(file):
with open(file) as f:
return sum(1 for content in f for char in content if char.lower() in 'aeiou')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.