1

入力として指定されたファイルからすべての行、単語、文字をカウントするプログラムを書いています。

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

ある程度、コードは大丈夫です。

ただし、ファイル内の「スペース」をカウントする方法はわかりません。私の文字カウンターは文字のみをカウントし、スペースは除外されます。
それに加えて、線を数えることに関しては空白を描いています。

4

4 に答える 4

11

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

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)

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

于 2013-01-19T16:52:07.760 に答える
4

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...

于 2014-04-15T20:38:42.807 に答える
0

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])
于 2017-08-31T07:12:10.297 に答える
-1

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);
于 2017-02-06T16:29:33.273 に答える