python计算fi中没有空格的字符

2024-09-30 14:23:59 发布

您现在位置:Python中文网/ 问答频道 /正文

如何计算没有空格的字符?我打错号码了。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: txtlenwithline数字open字符num
3条回答
words = line.split('\n')
num_words += len(words)

并不像你想的那样。在循环中

^{pr2}$

line是一个以'\n'结尾的字符串,因此line.split('\n')是一个两项列表,第一项包含除终止'\n'之外的行的所有字符;该列表中的第二项是空字符串。示例:

line = 'This is a test\n'
words = line.split('\n')
print(words, len(words))

输出

['This is a test', ''] 2

所以你的num_words += len(words)实际上并不计算单词,它只是行数的两倍。在

要获得line中单词的实际列表,您需要

words = line.split()

倒数第二行

num_charsx = num_chars - line.count(' ')

for循环之外,因此它从总计num_chars中减去文件最后一行的空间计数,但我假设您确实想从num_chars中减去整个文件的总空间计数。在

这是您代码的修复版本。在

num_words = 0
num_chars = 0
num_spaces = 0
with open(fname, 'r') as f:
   for num_lines, line in enumerate(f, 1):
       num_words += len(line.split())
       num_chars += len(line) - 1
       num_spaces += line.count(' ')

num_charsx = num_chars - num_spaces
print(num_lines, num_words, num_chars, num_spaces, num_charsx)

我修改了行读取循环以使用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方法删除“”,然后计算字符串的长度。在

num_chars = len(line.replace(' ', ''))

你也可以试试这个:

num_chars = 0
with open("C:/Python33/fire.txt",'r') as f:
    for line in f:
        num_chars += len(line.split('\n')[0])
    num_charsx = num_chars - line.count(' ')
print(num_charsx)

相关问题 更多 >