我正在编写一个程序来计算作为输入的文件中的所有行、单词和字符。
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) 作为字符长度。
您可以使用 .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_file: 循环更快一点)。
