basic python questions

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Sat Nov 18 10:33:17 CET 2006


In <1163829271.660193.70450 at j44g2000cwa.googlegroups.com>,
nateastle at gmail.com wrote:

> def Xref(filename):
>     try:
>         fp = open(filename, "r")
>         lines = fp.readlines()
>         fp.close()
>     except:
>         raise "Couldn't read input file \"%s\"" % filename
>     dict = {}
>     for line_num in xrange(len(lines)):

Instead of reading the file completely into a list you can iterate over
the (open) file object and the `enumerate()` function can be used to get
an index number for each line.

>         if lines[line_num] == "":  continue

Take a look at the lines you've read and you'll see why the ``continue``
is never executed.

>         words = lines[line_num].split()
>         for word in words:
>             if not dict.has_key(word):
>                 dict[word] = []
>             if line_num+1 not in dict[word]:
>                 dict[word].append(line_num+1)

Instead of dealing with words that appear more than once in a line you may
use a `set()` to remove duplicates before entering the loop.

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list