如何计算没有空格的字符?我打错号码了。num_charsx的正确数字是1761
num_words = 0
num_chars = 0
with open("C:/Python33/fire.txt",'r') as f:
for line in f:
words = line.split('\n')
num_words += len(words)
num_chars += len(line)
num_charsx = num_chars - line.count(' ')
print(num_charsx)
2064
Tags:
并不像你想的那样。在循环中
^{pr2}$line
是一个以'\n'
结尾的字符串,因此line.split('\n')
是一个两项列表,第一项包含除终止'\n'
之外的行的所有字符;该列表中的第二项是空字符串。示例:输出
所以你的
num_words += len(words)
实际上并不计算单词,它只是行数的两倍。在要获得
line
中单词的实际列表,您需要倒数第二行
在
for
循环之外,因此它从总计num_chars
中减去文件最后一行的空间计数,但我假设您确实想从num_chars
中减去整个文件的总空间计数。在这是您代码的修复版本。在
我修改了行读取循环以使用
enumerate
。这是获取行号和行内容的有效方法,而不必维护单独的行计数器。在在
num_chars += len(line) - 1
中,-1
是这样的,因此我们不在字符计数中包含每行的终止'\n'
。在请注意,在Windows上,文本文件行(通常)以
'\r\n'
结尾,但当您读取以文本模式打开的文件时,该终止符将转换为'\n'
。所以在Windows上,文件的实际字节大小是num_chars + 2 * num_lines
,假设最后一行有一个'\r\n'
结束符;它可能没有,在这种情况下,实际大小将比这个小2个字节。在您可能需要尝试用“”而不是'\n'来拆分行。因为'\n'应该由for循环完成。在
如果只需要字符计数,另一个选项是可以使用replace方法删除“”,然后计算字符串的长度。在
你也可以试试这个:
相关问题 更多 >
编程相关推荐