[Tutor] Working with lines from file and printing to another keeping sequential order
bob gailer
bgailer at gmail.com
Sun Apr 26 03:49:25 CEST 2009
Dan Liang wrote:
> Hi Bob and tutors,
>
> Thanks Bob for your response! currently I have the current code, but
> it does not work:
>
> [snip]
Thank you for code, sample data and more complete specs.
> Lines in the file look like following:
>
> word1 word2 word3 word4 yes
> word1 word2 word3 word4 no
> word1 word2 word3 word4 no
> word1 word2 word3 word4 no
> word1 word2 word3 word4 yes
> word1 word2 word3 word4 no
> word1 word2 word3 word4 yes
> word1 word2 word3 word4 no
> word1 word2 word3 word4 yes
> word1 word2 word3 word4 yes
> word1 word2 word3 word4 no
> word1 word2 word3 word4 no
> word1 word2 word3 word4 no
> word1 word2 word3 word4 yes
> word1 word2 word3 word4 no
> word1 word2 word3 word4 yes
> word1 word2 word3 word4 yes
> word1 word2 word3 word4 no
> word1 word2 word3 word4 no
> word1 word2 word3 word4 no
> word1 word2 word3 word4 no
> word1 word2 word3 word4 yes
>
> Any suggestions are appreciated. Also, I feel that my code is not the
> best way of solving the problem even if the problem of list indices is
> solved. Is my guess right?
Yes indeed. In actuality you need only to examine one line at a time and
keep track of the "state" of things.
In computer theory we refer to a "state machine". There is a set of
states. The program is always in exactly one of these states. In each
state there are actions to take and a (conditional) moves to other states.
the program starts in, let's say, state 0:
state 0: open file, goto state 1.
state 1: read next line, at eof goto state 6; if it ends in yes, goto
state 2 else stay in state 1.
state 2: read next line, at eof goto state 6; if it ends in yes stay in
state 2 else goto state 3.
state 3: read next line, at eof goto state 6. if it ends in yes goto
state 2 else print line and goto state 4.
state 4: read next line, at eof goto state 6. if it ends in yes goto
state 2 else print line and goto state 5.
state 5: read next line, at eof goto state 6. if it ends in yes goto
state 2 else stay in state 5.
state 6: close file and terminate
That can be implemented in Python as follows. This is not the prettiest
or most compact program, but is it a straightforward implementation of a
state machine.
state = 0 # initial state
data = open('test.txt')
while True: # iterate over lines
if state == 0: # look for first line ending in 'yes'
line = data.read().strip()
if line:
if line.endswith('yes'):
state = 1
else state = 6
elif state == 1:
# code for state i
# more states
elif state == 6:
data.close()
break
To simplify things I'd create a function to read and strip a line and
raise an exception at end of file.
--
Bob Gailer
Chapel Hill NC
919-636-4239
More information about the Tutor
mailing list