Newbie Question

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Tue Jun 20 20:30:38 EDT 2006


Saint Malo a écrit :
> BTW my program isn't about red blue yellow etc.  I'm just using it as
> an example.  I guess i didn't asked the question correctly or am not
> expressing myself correctly.   Let me try one more.
> 
> Ok.
> 
> Contents of text file follow:
> 
> red blue purble
> yellow blue green
> 
> 
> 
> Now lets imagine i wrote some code to look for the word red.  Once the
> program has found red i want it to print something like the following
> line.
> 
> 
> If you add red and blue you obtain the color purple...
> 
> 
> How do i turn each color in the line into a separate string? Now is
> that possible?
> 

Here's a possible solution - documenting it is left as an exercice to 
the reader... <g>

# data.txt
red blue purple
yellow blue green

# color.py
def read_data(path):
   f = open(path, 'r')
   try:
     return [tuple(line.strip().split()) for line in f]
   finally:
     f.close()

class ColorComboLookup(object):
   def __init__(self, data, search_in_results=True):
     index = dict()
     indices = range(search_in_results and 3 or 2)
     for combo in data:
        for i in indices:
         index.setdefault(combo[i], []).append(combo)
     self._index = index

   def __call__(self, color):
     try:
       return self._index[color]
     except KeyError:
       return []

def main(data_path):
   data = read_data(data_path)
   lookup = ColorComboLookup(data)
   for color in ['red', 'blue', 'yellow', 'green', 'pink']:
     print "looking for color", color
     combos = lookup(color)
     if combos:
       for combo in combos:
         print "If you add %s and %s you obtain the color %s..." % combo
     else:
       print "nothing found..."
   return 0

if __name__ == '__main__':
   import sys
   import os
   try:
     data_path = sys.argv[1]
   except IndexError:
     data_path = 'data.txt' # look in current dir
   if not os.path.is_file(data_path):
     sys.exit("data file %s not found" % data_path)
   sys.exit(main(data_path))

NB : not tested, but should work.



More information about the Python-list mailing list