从文件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()
在某种程度上,代码还可以。
但是,我不知道如何计算文件中的“空格”。我的角色计数器仅计算字母,空格除外。
另外,在计算行数时,我正在绘制空白。
-
您可以只使用
len(data)
字符长度。您可以
data
使用.splitlines()
方法按行拆分,结果的长度为行数。但是,更好的方法是逐行读取文件:
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:
循环更快一点的小缓冲区)。