Too Self Centered

Manuel M. Garcia mgarcia at cole-switches.com
Wed Jan 8 02:55:10 CET 2003


Python is very "self" centered! :-)

Your code is correct, and typical of Python.  Python programmers type
"self" a lot.  It is commonly complained about, but after programming
in Python for a while, now I prefer it.

You are not required to read "Style Guide for Python Code; PEP8", but
it is highly recommended:

http://www.python.org/peps/pep-0008.html

You can get rid of some "self"s by using
"x += 1" instead of "x = x + 1"
You use "+=" inconsistently.

Indent more than 1 space, Python uses indentation exclusively to
specify code blocks, so it helps to be able to see indents clearer.
Most people use 4 spaces.  Any coder's text editor will make this easy
for you.

Your program will blow up reading a large file because of your
recursive use of "subsequentRead(self)" and "subsequentLines(self)".
The form of recursion you are using is called "tail-recursion".
Python does not optimize tail-recursion.  Outside of the LISP world,
tail-recursion is not used (and rarely optimized).  A "while" loop
would be better.

Instead of "maketrans" and "translate", just use "replace".

I have no idea what your code is supposed to do, I will guess you wish
to count how many lines in a file, and then turn the newlines into
spaces to turn the multiline file into one long string.

This would be more typical:

# ###################################################### #

f = open('GNU-wordlist.txt').read()

number_lines = 0
if f:
    number_lines = f.count('\n') + 1

f = f.replace('\n',' ')

print """number_lines: %i
length of string f: %i
first 100 characters of f: %s""" % (number_lines, len(f), f[:100])

# ###################################################### #

but really, a file is usually turned into a list of lines, and all
processing done with that list:

# ###################################################### #

import random

s = open('GNU-wordlist.txt').read()

len_s = len(s)

list0 = s.split('\n')

del s

print """length of file: %i
number_lines: %i
20 random words: %s""" % (
    len_s,
    len(list0),
    ' '.join( [ random.choice(list0) for _ in range(20) ] )
    )

# ###################################################### #

Manuel





More information about the Python-list mailing list