counting characters and lines from a file python 2.7

不打扰是莪最后的温柔 提交于 2019-11-27 15:55:48

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

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

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

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!