简体   繁体   English

Python 中的字符计数

[英]Counting characters in Python

I am trying to write this program, which would tell me what's written in a text file and would also count the characters in that file.我正在尝试编写这个程序,它会告诉我在文本文件中写入了什么,并且还会计算该文件中的字符。 But I am stuck on the counting part.但我被困在计数部分。 Here is my code.这是我的代码。

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

here is the output:这是 output:

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

The issue is its count the words as a whole and not characters.问题是它把单词作为一个整体而不是字符来计算。 It should have said "There are 141 letters in the file" but it says 35. What am I doing wrong??它应该说“文件中有 141 个字母”,但它说 35。我做错了什么?

PS I am using Python 3.9.7 PS我正在使用Python 3.9.7

35 isn't the number of words in the file, it's the number of characters in the last line : 35 不是文件中的字数,而是最后line的字符数:

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

If you want to sum all the lengths of all the lines you'll want to do it in your loop:如果您想总结所有行的所有长度,您需要在循环中执行此操作:

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

Note that there's a difference between len(line) (the raw character count which includes punctuation, whitespace, etc) and the number of letters in the line:请注意, len(line) (包括标点符号、空格等的原始字符数)和行中的字母数之间存在差异:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM