如何只显示多行的总计数而不显示每行的计数?

How to only display the total count of a number of lines without the count being displayed every line?

我被指派在 .txt 文档中查找包含单词“发件人:”的某些行。我已经找到了所有这些,但我无法显示包含“发件人:”一词的总行数。我有一个计数器变量,但每次执行代码时,计数器都会显示在每一行之后(例如 1、2、3,而不是所有输出末尾的 27。请参见图片以供参考)。有人可以帮我解决这个问题吗?

email_file=open('mbox-short.txt','r')
counter=0
for line in email_file:
    if line.startswith("From:")==True:
        print(line.upper(),end="")
        counter+=1
        print(counter)
email_file.close()

Reference picture

你只需要将代码行print(counter)的位置改到末尾,这样它就不会每次循环都打印。

email_file=open('mbox-short.txt','r')
counter=0
for line in email_file:
    if line.startswith("From:")==True:
        print(line.upper(),end="")
        counter+=1
email_file.close()
print(counter)

这里的问题是这里的 print(counter) 语句 循环体内,所以它在每次迭代时打印(见缩进)。这应该可以解决问题:

email_file=open('mbox-short.txt','r')
counter=0
for line in email_file:
    if line.startswith("From:")==True:
        print(line.upper(),end="")
        counter+=1
print(counter)
email_file.close()

问题是您的 print 函数调用在 for 循环内对齐,这会导致每行后打印计数器的问题。

至于编码风格,您可以删除那个 ==True 东西,因为您已经有了用于测试的布尔值。我还建议使用更方便的 with 上下文管理器来处理文件。

简而言之(如果您不需要打印以“From:”开头的每一行):

with open('mbox-short.txt', 'r') as f:
    count = sum([line.startswith("From:") for line in f])
    print(count)