ay *_*mao 4 python file-io loops python-3.x
我正在编写一个用于计算文件中元音数量的赋值,目前在我的类中我们只使用这样的代码来检查文件的结尾:
vowel=0
f=open("filename.txt","r",encoding="utf-8" )
line=f.readline().strip()
while line!="":
for j in range (len(line)):
if line[j].isvowel():
vowel+=1
line=f.readline().strip()
Run Code Online (Sandbox Code Playgroud)
但是这次我们的任务由我们的教授给出的输入文件是一篇完整的文章,所以在整个文本中有几个空行来分隔段落和诸如此类的东西,这意味着我的当前代码只会计算到第一个空白行.
除了检查线路是否为空之外,有没有办法检查我的文件是否已到达终点?优选地,以类似的方式,我当前拥有我的代码,其中它检查while循环的每次迭代的某些内容
提前致谢
Ada*_*ith 19
不要以这种方式循环文件.而是使用for循环.
for line in f:
vowel += sum(ch.isvowel() for ch in line)
Run Code Online (Sandbox Code Playgroud)
事实上,你的整个计划只是:
VOWELS = {'A','E','I','O','U','a','e','i','o','u'}
# I'm assuming this is what isvowel checks, unless you're doing something
# fancy to check if 'y' is a vowel
with open('filename.txt') as f:
vowel = sum(ch in VOWELS for line in f for ch in line.strip())
Run Code Online (Sandbox Code Playgroud)
也就是说,如果你真的想继续使用一个while循环,原因有些误导:
while True:
line = f.readline().strip()
if line == '':
# either end of file or just a blank line.....
# we'll assume EOF, because we don't have a choice with the while loop!
break
Run Code Online (Sandbox Code Playgroud)