我正在編寫一個程序,用於計算輸入文件中的所有行,單詞和字符。從一個文件中計算字符和行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()
在某種程度上,代碼是好的。但是我不知道如何計算文件中的'空格'。我的字符計數器只計算字母,空格不包括在內。
另外,當談到計數線時,我正在畫一片空白。
太感謝你了。像它的魅力 – nutship
一樣工作,但如果你想不計算它的數量呢?我的意思是,如果你countNum = len(行)它會計數1更多,所以如果我把countNum = len(行)-1是一個好方法還是有一個更好的? –