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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14416522/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:24:38  来源:igfitidea点击:

counting characters and lines from a file python 2.7

pythonpython-2.7batch-filecountwords

提问by nutship

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

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.

但是,我不知道如何计算文件中的“空格”。我的字符计数器只计算字母,不包括空格。
另外,我在计算线数时画了一个空白。

采纳答案by Martijn Pieters

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

您可以只使用len(data)字符长度。

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

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

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)

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 保留的一个小缓冲区,以使for line in in_file:循环更快一点)。

回答by TougherApollo1

Very Simple: If you want to print no of chars , no of words and no of lines in the file. and including the spaces.. Shortest answer i feel is mine..

非常简单:如果您想打印文件中的字符数、单词数和行数。并包括空格.. 我觉得最短的答案是我的..

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

Keep coding buddies...

保持编码伙伴...

回答by GRS

This is one crude way of counting words without using any keywords:

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

#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);

回答by akp

read file-

读取文件-

d=fp.readlines()

characters-

人物-

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

lines-

线条-

len(d)

words-

字-

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