Reading from a file and converting it into a list of lines: code not working

Girish Sahani girish at cse.iitb.ac.in
Tue Jun 6 00:10:48 EDT 2006


I have a text file in the following format:

1,'a',2,'b'
3,'a',5,'c'
3,'a',6,'c'
3,'a',7,'b'
8,'a',7,'b'
.
.
.
Now i need to generate 2 things by reading the file:
1) A dictionary with the numbers as keys and the letters as values.
e.g the above would give me a dictionary like
{1:'a', 2:'b', 3:'a', 5:'c', 6:'c' ........}
2) A list containing pairs of numbers from each line.
The above formmat would give me the list as
[[1,2],[3,5],[3,6][3,7][8,7]......]

I wrote the following codes for both of these but the problem is that
lines returns a list like ["1,'a',2,'b'","3,'a',5,'c","3,'a',6,'c'".....] 
       Now due to the "" around each line,it is treated like one object
and i cannot access the elements of a line.

[code]
#code to generate the dictionary
def get_colocations(filename):
    lines = open(filename).read().split("\n")
    colocnDict = {}
    i = 0
    for line in lines:
        if i <= 2:
            colocnDict[line[i]] = line[i+1]
            i+=2
            continue
        return colocnDict
[/code]

[code]
def genPairs(filename):
    lines = open(filename).read().split("\n")
    pairList = []
    for line in lines:
        pair = [line[0],line[2]]
        pairList.append(pair)
        i+=2
        continue
return pairList
[/code]
Please help :((



More information about the Python-list mailing list