feed class from list

75 views Asked by At

I am still new to python but using it for my linguistics research.

So I am doing some research into toponyms, and I got a list of input data from a topographic institution, which looks like the following: Official_Name, tab, Dialect_Name, tab, Administrative_district, Topographic_district, Y_coordinates, X_coordinates, Longitude, Latitude.

So, I defined a class:

class MacroTop:
      def __init__(self, Official_Name, Dialect_Name, Adm_District, Topo_District, Y, X, Long, Lat):
          self.Official_Name = Official_Name
          self.Dialect_Name = Dialect_Name
          self.Adm_District = Adm_District
          self.Topo_District = Topo_District
          self.Y = Y
          self.X = X
          self.Long = Long
          self.Lat = Lat

So, with open(), I wanted to load my .txt file with the data I have to read it into the class using a loop but it did not work.

The result I want is to be able to access a feature of the class, say, Dialect_Name and be able to look through all the entries of that feature. I can do that just in the loop, but I wanted to define a class so I could be able to do more manipulation afterwards.

my loop:

with open("locLuxAll.txt", "r") as topo_list:
    lines = topo_list.readlines()
    for line in lines:
        line = line.split('\t')
        print(line)
        print(line[0])  # This would access all the data that is characterized as Official_Name

I tried to make another loop:

for i in range(0-len(lines)):
        lines[i] = MacroTop(str(line[0]), str(line[1]), str(line[2]), str(line[3]), str(line[4]), str(line[5]), str(line[6]), str(line[7]))

But that did not seem to work.

1

There are 1 answers

5
Pythonist On

This line fails:

for i in range(0-len(lines)):

You're trying to loop through negative number I guess, so the output will be an empty list.

In [11]: [i for i  in range(-200)]
Out[11]: []

EDIT: Your code seems unreadable to me, you have for i in range(len(lines)) but in this for loop, you're iterating through line variable, where is it from? First of all I'd not write back to lines list as it comes from readlines. Create new list for that, and you dont need i variable, those lines will be kept in order anyway.

class_lines = []
for line in lines:
    class_lines.append(MacroTop(str(line[0]), str(line[1]), str(line[2]), str(line[3]), str(line[4]), str(line[5]), str(line[6]), str(line[7])))

Or even with list comprehension:

class_lines = [MacroTop(str(line[0]), str(line[1]), str(line[2]), str(line[3]), str(
    line[4]), str(line[5]), str(line[6]), str(line[7])) for line in lines]