如何在Python中循环直到文件结束而不检查空行?

2024-04-28 13:16:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一个作业来计算一个文件中的元音个数,目前在我的类中,我们只使用这样的代码来检查文件的结尾:

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

但是这次我们的作业,教授给的输入文件是一篇完整的论文,所以整个课文中有几行空白,用来分隔段落和其他内容,这意味着我当前的代码只能计算到第一行空白。

除了检查行是否为空之外,是否有其他方法检查我的文件是否已到达其结尾?最好采用与我目前的代码类似的方式,它在while循环的每个迭代中检查某些内容

提前谢谢


Tags: 文件代码内容readline结尾作业lineopen
3条回答

我在遵循上述建议时发现 对于f行: 不适用于pandas数据帧(不是任何人说的那样) 因为数据帧中的文件结尾是最后一列,而不是最后一行。 例如,如果有一个包含3个字段(列)和9个记录(行)的数据帧,则for循环将在第3次迭代后停止,而不是在第9次迭代后停止。 特蕾莎

不要这样循环浏览文件。而是使用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

查找文件的结束位置:

f = open("file.txt","r")
f.seek(0,2) #Jumps to the end
f.tell()    #Give you the end location (characters from start)
f.seek(0)   #Jump to the beginning of the file again

然后您可以:

if line == '' and f.tell() == endLocation:
   break

相关问题 更多 >