如何在不检查空行的情况下在Python中进行while循环直到文件结束? [英] How to while loop until the end of a file in Python without checking for empty line?

查看:354
本文介绍了如何在不检查空行的情况下在Python中进行while循环直到文件结束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个作业以计算文件中的元音数量,目前在我的课堂上,我们仅使用如下代码检查文件结尾:

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()

但是这次我们的教授分配的输入文件是一整篇论文,因此,在全文中有几行空白行用于分隔段落,而没有其他内容,这意味着我当前的代码将一直计数到第一行空白行为止. /p>

除了检查行是否为空白以外,是否有其他方法可以检查文件是否已到达末尾?最好以与我当前使用的代码相似的方式,在该代码中,while循环的每个单次迭代都会检查某些东西

预先感谢

解决方案

不要以这种方式遍历文件.而是使用for循环.

for line in f:
    vowel += sum(ch.isvowel() for ch in line)

实际上,您的整个程序就是:

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())

也就是说,如果出于某些误导原因,您真的想继续使用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

I'm writing an assignment to count the number of vowels in a file, currently in my class we have only been using code like this to check for the end of a file:

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()

But this time for our assignment the input file given by our professor is an entire essay, so there are several blank lines throughout the text to separate paragraphs and whatnot, meaning my current code would only count until the first blank line.

Is there any way to check if my file has reached its end other than checking for if the line is blank? Preferably in a similar fashion that I have my code in currently, where it checks for something every single iteration of the while loop

Thanks in advance

解决方案

Don't loop through a file this way. Instead use a for loop.

for line in f:
    vowel += sum(ch.isvowel() for ch in line)

In fact your whole program is just:

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())

That said, if you really want to keep using a while loop for some misguided reason:

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

这篇关于如何在不检查空行的情况下在Python中进行while循环直到文件结束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆