计算行中的字符数

-1 投票
2 回答
10850 浏览
提问于 2025-04-18 04:49

我需要计算一行中的字符数量。
我尝试了很多找到的方法,但它们的输出结果都不对。

我尝试过:

with file as f:
     for line in file:
         chars = len(line)

但是输出结果差了大约200个字符。

最后我做了这个:

with file as f:
for line in f:
    self.length += 1
    self.count = len(list(line.strip('\n')))

这样可以返回行数和最后一行的字符数量。

编辑:我不明白为什么我问一个明显符合所有规则的问题还会被投反对票。

2 个回答

0

如果你想要获取每一行的长度,而不仅仅是最后一行,可以使用下面的代码:

with open('file.txt') as myfile:
    for line in file:
        print len(line)

运行示例:

file.txt

Hello there,

What is your name?

Bye

预期输出

13
1
19
1
4

实际输出

>>> with open('file.txt') as myfile:
...     for line in myfile:
...             print len(line)
... 
13
1
19
1
4
>>> 

如果你在想,为什么看起来是空的一行却有长度为一,那是因为在Python中,换行符被保存为'\n'。实际的文件内容是这样的:

>>> myfile = open('file.txt').read()
>>> myfile
'Hello there,\n\nWhat is your name?\n\nBye\n'
>>> 

但是当你调用print时,它会把这些转义字符转换成换行:

>>> myfile = open('file.txt').read()
>>> print myfile
Hello there,

What is your name?

Bye

>>> 
1

我猜你是在从一个文本文件里读取行。

为什么不使用 .splitlines() 或 .strip() 把每一行添加到一个列表里呢?这样你就可以对列表中的每个元素使用 len( ) 函数来计算长度。

*编辑:修改了措辞

撰写回答