计算文件python 2.7中的字符和行

nut*_*hip 1 python words batch-file count 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()
Run Code Online (Sandbox Code Playgroud)

在某种程度上,代码是可以的.

但我不知道如何计算文件中的"空格".我的角色计数器只计算字母,空格被排除在外.
另外,我在计算线条时画了一个空白.

Mar*_*ers 11

你可以使用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)
Run Code Online (Sandbox Code Playgroud)

现在,即使文件非常大,程序也能正常工作; 它不会在内存中一次保存多行(加上python保持的小缓冲区使for line in in_file:循环更快一些).