繁体   English   中英

从文件python 2.7计算字符和行

[英]counting characters and lines from a file 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)作为字符长度。

您可以使用.splitlines()方法按行拆分data ,结果的长度为行数。

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

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:for line in in_file:循环快一点)。

非常简单:如果要打印的字符数不为,则文件中的单词和行数均不打印。 包括空格。.我觉得最短的答案是我的..

import string
data = open('diamond.txt', 'r').read()
print len(data.splitlines()), len(string.split(data)), len(data)

保持编码伙伴...

读取文件

d=fp.readlines()

字符-

sum([len(i)-1 for i in d])

线

len(d)

话-

sum([len(i.split()) for i in d])

这是不使用任何关键字的单词计数的一种粗略方法:

#count number of words in file
fp=open("hello1.txt","r+");
data=fp.read();
word_count=1;
for i in data:
    if i==" ":
        word_count=word_count+1;
    # end if
# end for
print ("number of words are:", word_count);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM