[Tutor] Parsing a primitive line of logic

Scot W. Stevenson scot@possum.in-berlin.de
Mon, 14 Oct 2002 09:54:18 +0200


Hello there, 

I'm trying to write a little piece that will let people search for keywords 
in, say, a text, so that given "Mary had a little lamb" they can write a 
query such as "Mary & lamb" and get "true", or "Mary & ! cow" and get 
true, too. 

The following code works, but somehow I'm not sure if it the right way to 
doit, first of all because it contains the eval(), which makes me as 
nervous as using exec(), and second because it seems like I'm wasting 
computer power be setting up the whole string for evaluation even if say 
the first term is negative. 

This can't be a new problem, in fact, I'm sure this is Programming 101. Any 
suggestions on what could be done better?

Thank you, 
Y, Scot

===============================================

teststr = """This is one of those strings that has lots of animals in them:
    cat, dog, pig, mouse, emu, frog, and gopher. There are animals missing,
    but you'll have to find out which ones"""
    
parsedict = {'&' : 'and',
             '|' : 'or', 
             '!' : 'not',
             '(' : '(',
             ')' : ')'}

inputstring = ''
while inputstring != 'quit':
    inputstring = raw_input('Give me a search string please: ')
    words = inputstring.split()
    parselist = []

    for token in words:
        try:
            converted = parsedict[token]
        except KeyError:
            if token[0] == '"' and token[-1] == '"':
                token = token[1:-1]
            converted = teststr.count(token)
        parselist.append(str(converted))

    evalstring = ' '.join(parselist)
    if eval(evalstring):
        print '%s is true' % inputstring
    else:
        print '%s is false' % inputstring

================================================

-- 
   Scot W. Stevenson wrote me on Monday, 14. Oct 2002 in Zepernick, Germany   
       on his happy little Linux system that has been up for 323 hours        
        and has a CPU that is falling asleep at a system load of 0.00.