从文件的Python 2.7计数字符和线条 [英] counting characters and lines from a file python 2.7

查看:132
本文介绍了从文件的Python 2.7计数字符和线条的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在做我的功课。

我正在写计算所有行数,字数和字符从作为输入文件的程序。

I'm writing a program that counts all lines, words and characters from a file given as input.

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()

要一定程度上,code是ok了。

To some extent, the code is ok.

我不知道但是如何在文件中算'空间'。我的性格计数器计数只有字母,空格被排除在外。结果
再加上我画一个空白,当谈到计数线。

I don't know however how to count 'spaces' in the file. My character counter counts only letters, spaces are excluded.
Plus I'm drawing a blank when it comes to counting lines.

任何帮助AP preciated。

Any help appreciated.

推荐答案

您可以只用 LEN(数据)的字符长度。

You can just use len(data) for the character length.

您可以分割数据使用的 .splitlines() 的方法,并且该结果的长度是行数

You can split data by lines using the .splitlines() method, and length of that result is the number of lines.

但是,一个更好的方法是逐行读取文件中的行:

But, a better approach would be to read the file line by line:

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会做出在in_file中的行:循环快一点)。

Now the program will work even if the file is very large; it won't hold more than one line at a time in memory (plus a small buffer that python keeps to make the for line in in_file: loop a little faster).

这篇关于从文件的Python 2.7计数字符和线条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆