Python help for a C++ programmer

Neil Cerutti mr.cerutti at gmail.com
Wed Jan 16 09:42:33 EST 2008


On Jan 16, 2008 9:23 AM, mlimber <mlimber at gmail.com> wrote:
> I'm writing a text processing program to process some survey results.
> I'm familiar with C++ and could write it in that, but I thought I'd
> try out Python. I've got a handle on the file I/O and regular
> expression processing, but I'm wondering about building my array of
> classes (I'd probably use a struct in C++ since there are no methods,
> just data).
>
> I want something like (C++ code):
>
>  struct Response
>  {
>    std::string name;
>    int age;
>    int iData[ 10 ];
>    std::string sData;
>  };
>
>  // Prototype
>  void Process( const std::vector<Response>& );
>
>  int main()
>  {
>    std::vector<Response> responses;
>
>    while( /* not end of file */ )
>    {
>      Response r;
>
>      // Fill struct from file
>      r.name = /* get the data from the file */;
>      r.age = /* ... */;
>      r.iData[0] = /* ... */;
>      // ...
>      r.sData = /* ... */;
>      responses.push_back( r );
>    }
>
>     // Do some processing on the responses
>     Process( responses );
>  }
>
> What is the preferred way to do this sort of thing in Python?

It depends on the format of your data (Python provides lots of
shortcuts for handling lots of kinds of data), but perhaps something
like this, if you do all the parsing manually:

class Response(object):
    def __init__(self, extern_rep):
        # parse or translate extern_rep into ...
        self.name = ...
        self.age = ...
        # Use a dictionary instead of parallel lists.
        self.data = {...}
    def process(self):
        # Do what you need to do.

fstream = open('thedatafile')

for line in fstream:
    # This assumes each line is one response.
    Response(line).process()

-- 
Neil Cerutti <mr.cerutti+python at gmail.com>



More information about the Python-list mailing list