计算 Python 中的字符数

Counting characters in Python

我正在尝试编写这个程序,它会告诉我文本文件中写了什么,还会计算该文件中的字符数。但我被困在计数部分。这是我的代码。

def read_file(filename):
    infile = open(filename)
    
    
    for line in infile:
        print (line, end = "")
    print()
    
    print("There are",len(line),"letters in the file")
    
    infile.close() 

这是输出:

Humpty Dumpty sat on a wall,
Humpty Dumpty had a great fall.
All the king's horses and all the king's men
Couldn't put Humpty together again.
There are 35 letters in the file

问题是它计算的是整个单词而不是字符。它应该说“文件中有 141 个字母”,但它说是 35 个。我做错了什么??

P.S 我正在使用 Python 3.9.7

35不是文件的字数,是最后的字符数line:

>>> len("Couldn't put Humpty together again.")
35

如果你想对 all 的长度求和 all 你想在循环中执行的行的长度:

    file_len = 0 
    for line in infile:
        print(line, end = "")
        file_len += len(line)
    print()

    print(f"There are {file_len} letters in the file")

请注意,len(line)(包括标点符号、空格等的原始字符数)与行中 个字母 的数量之间存在差异:

>>> sum(c.isalpha() for c in "Couldn't put Humpty together again.")
29