[Tutor] Looping problem
Rich Krauter
rmkrauter at yahoo.com
Thu Aug 12 20:49:42 CEST 2004
Hi Vicki,
Here is what I tried; its not fully tested, but maybe
it'll help. I just tried to get rid of some of the
nested loops.
<code>
import cStringIO
import sys
def tokenize(arg):
"""
Turn each line into a collection of tokens,
and return list of tokens.
"""
arg = arg.strip()
tokens = []
tok = ''
for c in arg:
if c == '<' or c == '>':
if tok:
tokens.append(tok)
tok = ''
continue
tok += c
return tokens
if __name__ == '__main__':
# pretend sys.stdout is your port
port = sys.stdout
# substitute what you really want to send
token_map = {'ACK': 'send ACK',
'ETX': 'send ETX',
'STX': 'send STX'}
f = """Load Time Resolve Data
ab<TAB><TAB>11<CR><ACK>
<STX>04142069<ETX><ACK>
<STX>08000000006E<ETX><ACK>
<STX>0414106A<ETX><ACK>
<STX>10169100000000000061<ETX><ACK>
<STX>10169000000000000060<ETX><ACK>
<STX>1016934129CD4CCB201E<ETX><ACK>
<STX>10169200000000000062<ETX><ACK>
<STX>10169500000000000065<ETX><ACK>
<STX>10169400000000000064<ETX><ACK>
<STX>20170000000281082A07D4021A0000000815<EOT><ACK><ACK>
"""
# pretend string f is your file
strIO = cStringIO.StringIO(f)
LTRD_START = False
for readString in strIO:
if "Load Time Resolve Data" in readString:
LTRD_START = True
continue
if "ab<TAB><TAB>11<CR><ACK>" in readString:
continue
if LTRD_START:
tt = tokenize(readString)
for t in tt:
if t == 'EOT':
print 'Breaking out of loop ...'
break
if t in token_map:
port.write('%s\n'%token_map[t])
else:
print t
</code>
Good luck.
Rich
More information about the Tutor
mailing list