Tim Chase
1/16/2008 2:56:00 PM
> 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?
Without knowing more about the details involved with parsing the
file, here's a first-pass whack at it:
class Response(object):
def __init__(self, name, age, iData, sData):
self.name = name
self.age = age
self.iData = iData
self.sData = sData
def __repr__(self):
return '%s (%s)' % self.name
def parse_response_from_line(line):
name, age, iData, sData = line.rstrip('\n').split('\t')
return Response(name, age, iData, sData)
def process(response):
print 'Processing %r' % response
responses = [parse_response_from_line(line)
for line in file('input.txt')]
for response in responses:
process(response)
That last pair might be condensed to just
for line in file('input.txt'):
process(parse_response_from_line(line))
Things get a bit hairier if your input is multi-line. You might
have to do something like
def getline(fp):
return fp.readline().rstrip('\n')
def response_generator(fp):
name = None
while name != '':
name = getline(fp)
age = getline(fp)
iData = getline(fp)
sData = getline(fp)
if name and age and iData and sData:
yield Response(name, age, iData, sData)
fp = file('input.txt')
for response in response_generator(fp):
process(response)
which you can modify accordingly.
-tkc