2013-01-19 22 views
1

我正在編寫一個程序,用於計算輸入文件中的所有行,單詞和字符。從一個文件中計算字符和行python 2.7

import string 

def main(): 
    print "Program determines the number of lines, words and chars in a file." 
    file_name = raw_input("What is the file name to analyze? ") 

    in_file = open(file_name, 'r') 
    data = in_file.read() 

    words = string.split(data) 

    chars = 0 
    lines = 0 
    for i in words: 
     chars = chars + len(i) 

    print chars, len(words) 


main() 

在某種程度上,代碼是好的。但是我不知道如何計算文件中的'空格'。我的字符計數器只計算字母,空格不包括在內。
另外,當談到計數線時,我正在畫一片空白。

回答

11

您只能使用len(data)作爲字符長度。

您可以使用.splitlines()方法按行分割data,該結果的長度爲行數。

但是,更好的方法是逐行讀取文件中的行:

chars = words = lines = 0 
with open(file_name, 'r') as in_file: 
    for line in in_file: 
     lines += 1 
     words += len(line.split()) 
     chars += len(line) 

現在,如果該文件是非常大的程序會甚至工作;它不會在內存中一次保存超過一行(加上python保留的小緩衝區,以使for line in in_file:循環更快一點)。

+0

太感謝你了。像它的魅力 – nutship

+0

一樣工作,但如果你想不計算它的數量呢?我的意思是,如果你countNum = len(行)它會計數1更多,所以如果我把countNum = len(行)-1是一個好方法還是有一個更好的? –

4

非常簡單: 如果您想打印字符數,文字中沒有文字和行數。和包括空格..簡短的回答我覺得是我的..

import string 
data = open('diamond.txt', 'r').read() 
print len(data.splitlines()), len(string.split(data)), len(data) 

保持編碼哥們......

-1

這是不使用任何關鍵字字數統計的一個粗暴的方式:

#count number of words in file 
fp=open("hello1.txt","r+"); 
data=fp.read(); 
word_count=1; 
for i in data: 
    if i==" ": 
     word_count=word_count+1; 
    # end if 
# end for 
print ("number of words are:", word_count); 
+0

這並沒有解決這個問題。海報已經在計算單詞,並且還要計算字符和線條。 – teppic

0

讀取文件 -

d=fp.readlines() 

characters-

線 -

len(d) 

words-

sum([len(i.split()) for i in d]) 
相關問題