Translation in python of C++ idiom

brueckd at tbye.com brueckd at tbye.com
Fri Aug 9 13:16:51 EDT 2002


On Fri, 9 Aug 2002, Francois Petitjean wrote:

> In a paper entitled "Minimalism: Omit Needless Code" (1), Kevlin Henney
> advocates a concise coding style and for instance the following snippet :
> typedef std::istream_iterator<std::string> in;
> std::cout << std::distance(in(std::cin), in());
> is given to print the number of words in a textfile or stream. And by
> replacing the typedef by
> typedef std::istreambuf_iterator<char> in;
> we count chars.
> 
> To print the number of lines :
> typedef std::istreambuf_iterator<char> in;
> std::cout << std::count(in(std::cin), in(), '\n');

Are you sure the paper wasn't entitled "Minimalism: Kelvin's Guide to
Unreadable Code Spew"? :) For me, the density of that code is 
intolerable.

> So, what would be the equivalent in Python?

We all generally advocate a *readable* coding style. In any case, to count
chars:

count = os.path.getsize(somefile)

To count words (assuming no memory constraints):

data = open(somefile.read())
count = len(data.split())

To count lines:
data = open(somefile.read())
count = data.count('\n') + 1

-Dave





More information about the Python-list mailing list