2017-04-15 112 views
1

你如何计算charcters与空格?我没有得到正确的数字。 num_charsx的正确数目是1761python计算文件中没有空格的字符

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 

回答

0
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个字节。

0

您可能想尝试使用''而不是'\ n'来分割行。由于'\ n'应该由for循环完成。

另一个选项,如果你只是想要一个字符计数,你可以使用替换方法来删除'',然后计算字符串的长度。

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

你也可以试试这个:

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

你可以试试这个:

num_char = 0 
f = open("C:/Python33/fire.txt") 
word_list = ' '.join(f.read().splitlines()).split() 
for x in word_list: 
    num_char += len(x) 
print(num_char) 
相关问题