user6437583 user6437583 - 5 months ago 13
Python Question

Creating objects in python within a formatted text file

I have a text file that is formatted as such:

T timestamp
U username
W text


Is there a way to create an object within the text file with the T U and W being attributes? I have only done scripting in Python and nothing object orientated so I'm a bit lost.

I need to parse this giant text file and I am currently reading the file, line by line, looking for the 'W' attribute but it might be more useful to have the entire object.

edit: it looks like this

total number:18572084
T 2009-06-01 21:43:59
U http://twitter.com/burtonator
W No Post Title

T 2009-06-01 21:47:23
U http://twitter.com/burtonator
W No Post Title

T 2009-06-02 01:15:44
U http://twitter.com/burtonator
W No Post Title

T 2009-06-02 05:17:52
U http://twitter.com/burtonator
W No Post Title

jDo jDo
Answer

You only need one way of doing it but here's two variations and a single file reading function that doesn't read the entire file at once (it stores 3-4 lines at most):

# **kwarg is a dictionary. It can hold any number of keyword arguments.
class obj1:
    def __init__(self, **kwarg):
        self.attributes = kwarg

# t,u,v as actual class attributes
class obj2:
    def __init__(self, t, u, w):
        self.t = t
        self.u = u
        self.w = w

objects1 = []
objects2 = []

with open("input_file", "r") as f:
    lines = []
    for line in f:
        line = line.strip()
        lines.append(line)
        if line.startswith("W"):
            objects1.append(obj1(t=lines[-3], u=lines[-2], w=lines[-1]))
            objects2.append(obj2(t=lines[-3], u=lines[-2], w=lines[-1]))
            lines = []


# same output but different ways of accessing the attributes

for o in objects1:
    print o.attributes["t"]
    print o.attributes["u"]
    print o.attributes["w"]

for o in objects2:
    print o.t
    print o.u
    print o.w

input file:

$ cat input_file 
total number:18572084
T   2009-06-01 21:43:59
U   http://twitter.com/burtonator 
W   No Post Title

T   2009-06-01 21:47:23
U   http://twitter.com/burtonator
W   No Post Title

T   2009-06-02 01:15:44
U   http://twitter.com/burtonator
W   No Post Title