Writing dictionary to file (web code)

Mike Brenner mikeb at mitre.org
Fri Sep 8 22:53:51 CEST 2000


Gustav > Hi, I'm looking for an elegant way to write a dictionary to a
file.


Since the task is elegance not efficiency, it is possible to use the
fact that the worldwide web is a distributed, associative dictionary.
Put each element of the dictionary on its own web page, then have one
extra web page that has a hyperlink to each of those web pages. The
human brain works a lot like that.

The following python code shows how to do this.

# python-dictionary-to-web (dict2web) script

# PUT DICTIONARY HERE:
x ={"apple fruits": "apples are green Fall fruits that like to go into
pies",
   "peaches": "peaches are orange Georgia fruits that like to go into
jams",
   "bing cherries": "cherries are black Northwest fruits that like to go
BING!",
   "bananas": "fruit flies like a banana and time flies like a ..."}

for i in x.keys(): print i

output_directory="C:/tmp/"
print "The output_directory is ["+output_directory+"]"
 
import string
import sys
import time

black =      "000000";
grey =       "222222";
red =        "880000";
dark_red =   "ff0000";
orange =     "ff8822";
yellow =     "448822";
dark_green = "00ff00";
green =      "008800";
cyan =       "00ffff";
blue =       "0000ff";
dark_blue =  "0000ff";
purple =     "ff00ff";
brown =      "888844";
white =      "ffffff";

def iu(message): # insert underlines for blanks
  result=""
  for i in message:
    if   i==' ':result=result+'_'
    elif i=='/':result=result+'-'
    elif i==':':pass
    else: result=result+i
  return result

def low_level(hue="#00FF00#",
              key="key",
              data="data",
              time=time.ctime(time.time()),
              file="Cdummy.htm"): 
  g=open(output_directory+file,'w+')
  g.write('<html><head><title>DICTIONARY-2-WEB.COM
(member)</title></head>')
  g.write('<body stylesrc="http://Default.htm">')
  g.write('<p>Data ['+data+']</p>')
  g.write('<p>Key ['+key+"] became ["+iu(key)+"] at ["+time+']</p>')
  g.write('<p>&nbsp; </p>')
  g.write('</body>')
  g.write('</html>')
  g.close()

k=open(output_directory+"index.htm",'w+')
k.write('<html><head><title>DICTIONARY-2-WEB.COM (top)</title></head>')
k.write('<body stylesrc="http://Default.htm">')
for i in x.keys():
  ukey=iu(i)
  low_level(key=i, data=x[i], file=ukey+'.htm')
  k.write("<p><a href="+ukey+".htm><font
face=Arial><small>"+i+"</small></font></a>")
  print "finished writing to the file ["+ukey+']'
k.write('</body>')
k.write('</html>')
k.close()





More information about the Python-list mailing list