dynamically creating classes from text

Chris Angelico rosuav at gmail.com
Tue Jan 24 12:42:20 EST 2012

On Wed, Jan 25, 2012 at 4:22 AM, T H <turian9000 at gmail.com> wrote:
> I’m new to python, sorry if my question is a bit naive, I was
> wondering if it is possible to parse some text (ie. from a text file
> or say html) and then dynamically create a class?

Presuming that your class name comes from somewhere (eg the name of
the text file), yes, you can do that!

What I'd do is parse the file and write out another text file
containing the Python code. If you then need that in the current
session, you could import or eval it. That's likely to be the easiest
solution, I think.

This is a fairly straightforward text processing question. Personally,
I would be inclined to simplify the input file's format; perhaps
something like this:

bark numberBarks
run howFast howLong

Less clutter, just the content you need. Either way, though, all you
need to do is iterate over the lines in the file, parse them to get
what you need, and write out a function definition for each one -
something like this:

out = open("output.py","wt")  # you'll want a better file name
out.write("class Dog:\n") # or whatever class name you need
for line in open("input.txt","t"):  # use 'with' if you want to learn
about that feature
    words=line.split(" ")
    out.write("\tdef "+words[0]+"(self, "+", ".join(words[1:])+", myArg):\n")
    for word in words[1:]:
        out.write("\t\tprint('"+word+": '+"word+")\n")

This will more or less do what you want, though with my simpler file
format. Play around with text parsing functions in the standard
library to make it read another format.

Python's pretty good at manipulating text. Whatever you want to do,
you can do fairly easily.


More information about the Python-list mailing list