2017-04-15 69 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)