words = line.split('\n')
num_words += len(words)
没有做你认为它做的事。在循环中
for line in f:
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 个字节。