Newbie question: Any way to improve this code?

Duncan Smith buzzard at urubu.freeserve.co.uk
Fri Dec 5 19:06:16 EST 2003


"Gustavo Campanelli" <birdiepageANTI at SPAMciudad.FILTERcom.ar> wrote in
message news:bqqvnl$kbo$1 at taurus.webcorp.pl...
> I'm begining to work in a program that cicles through a list of phrases
> (basically, a changing signature file). I started yesterday, and I only
> have abput 8 full hours of real Python experience.
>
> So far I produced a code that succesfully reads an process the file,
> separating the phrases. Is there any way to optimize this code, so that
> I don't have to use the if for the first list member?
>
> Now for the data.
> The file is firmas.txt, it contains the following three example phrases
>
> Frase 1
> Frase 2
> Frase 3
>
> Note that this phrases are separated by newline characters. Upon reading
> the full file (it won't be long) I get this:
>
> 'Frase 1\nFrase 2\nFrase 3\n'
>
> so, as you can see, the newlines are there.
>
> My code is this (I know I should close the file, but so far the runtime
> is so small it doesn't really matter, that'll change)
>
> import string

the string module doesn't seem to be used

> f = open("firmas.txt",'r') # open the file
> texto = f.read ()

no need for the space before the parentheses (see
http://www.python.org/peps/pep-0008.html)

> n = range (len (texto))
> frases = [0]

why not initialise an empty list and append to it?

> frase =""
> cant = 0
> for a in n:
>      if texto [a] != "\n":
>         frase = frase + (texto [a])
>      else:
>          if cant == 0:
>              frases [0] = frase
>          else:
>              frases.append (1)
>              frases [cant] = frase

then you can replace the above 5 lines with the following line and remove
all references to 'cant',

            frases.append(frase)

>          cant +=1
>          frase = ""
>

Or you could replace the whole thing with,

try:
    f = open("firmas.txt",'r')
    texto = f.read()
    frases = texto.split('\n')[:-1]
finally:
    f.close()

Duncan







More information about the Python-list mailing list