Chinaunix首页 | 论坛 | 博客
  • 博客访问: 27286
  • 博文数量: 10
  • 博客积分: 170
  • 博客等级: 入伍新兵
  • 技术积分: 90
  • 用 户 组: 普通用户
  • 注册时间: 2011-04-26 10:48
文章分类

全部博文(10)

文章存档

2011年(10)

最近访客

分类: Python/Ruby

2011-05-06 15:44:54

          学习的过程中会遇到很多单词,有时候我就像把这些单词记录下来,下次可以方便查询,加上我的英语就那样,我需要有一种查询可以“模糊匹配“,比如我输入“et“,会出来包含“et“的所有单词。于是我写了一个“能用就行“的单词查询程序,用一段时间就改进一些,也尝试了GUI设计,个人觉得GUI查询单词效率很低,于是回归CLI(命令行接口)程序。
代码如下,算是备份:
  1. #!/usr/bin/env python

  2. """
  3.    The Program Name: mydict.py
  4.    
  5.    This program will save the word pair as a dictionary.It can query,list,update,
  6.    add,delete word,and view version or exit.
  7.    
  8.    Copyright (C) 1989,1999 Free Software Foundation,Inc.
  9.    
  10.    Copyleft (C) 2011 ClownFish(pythonisland@gmail.com)
  11.    
  12. """
  13. #Program: mydict.py
  14. #Author: clownfish
  15. #Date: 2011/04/02
  16. #Rev: 4.1Beta
  17. #Plotform: Ubuntu



  18. import re        
  19. import os.path,os


  20. def help():
  21.     "get help information"
  22.     print "\n========Help Mode===== '#' to quit this mode=="
  23.     print '\n\n'
  24.     print '''\n\n Hi,Welcome to MyDictionary.You may be want to have a dictionary just for yourself in you life.So I share it with you free.But if you want to update it,you should to tell user the mydictionary is based on my name,please!'''    
  25.     print '\n\n'
  26.     if (raw_input(" next step by enter anything >>> ").strip().lower()) == '#':
  27.         print 'You have quited this mode!'
  28.         return    
  29.     print '''\n\n (1).the function listWord(),you have to input the word's fist byte in [a-z],and if you dont do that,the function will not work.And you should input something about the word,if you input nothing ,the dictionary will list all the words begin with you have just inputed first word.\n\n'''
  30.     if raw_input(" next step by enter anything >>> ").strip().lower() == '#':
  31.         print 'You have quited this mode!'
  32.         return    
  33.     print '''\n\n (2).the functiom addWord(),you can add the word .I want to make it work faster,so you should input the first byte right.\n\n'''
  34.     if raw_input(" next step by enter anything >>> ").strip().lower() == '#':
  35.         print 'You have quited this mode!'
  36.         return    
  37.     print '''\n\n (3).the function updateWord(),if you have found a error word or you want to update a word,the this function will give you surprise.\n\n'''
  38.     if raw_input(" next step by enter anything >>> ").strip().lower() == '#':
  39.         print 'You have quited this mode!'
  40.         return    
  41.     print '''\n\n (4).the function deleteWord(),you may input a error word and you want to delete it.Just do it!\n\n'''
  42.     if raw_input(" next step by enter anything >>> ").strip().lower() == '#':
  43.         print 'You have quited this mode!'
  44.         return    
  45.     print '''\n\n (5).the function queryWord() ,you have to input a right word,then you will get it's meaning.If you want to get some surprise,you should add a new word with interesting ^_^\n\n'''
  46.     if raw_input(" next step by enter anything >>> ").strip().lower() == '#':
  47.         print 'You have quited this mode!'
  48.         return    
  49.     print '''\n\n (6).the function saveDT(),I need to make it work faster,but if you dont use the function,the new word which you have just added will not save in you harddisk,so if you want to use it safety,you should use it,good luck.\n\n'''
  50.     if raw_input(" next step by enter anything >>> ").strip().lower() == '#':
  51.         print 'You have quited this mode!'
  52.         return    
  53.     print '''\n\n (7).the function exit(),means you have got you work,have a good time.\n\n'''
  54.     if raw_input(" next step by enter anything >>> ").strip().lower() == '#':
  55.         print 'You have quited this mode!'
  56.         return    
  57.     print '''\n\n (8).the function version(),get some inforamtion about me,zhubuntu...\n\n'''
  58.     if raw_input(" next step by enter anything >>> ").strip().lower() == '#':
  59.         print 'You have quited this mode!'
  60.         return    
  61.     print '''\n\n (9).the test function main()\n\n'''
  62.     if raw_input(" next step by enter anything >>> ").strip().lower() == '#':
  63.         print 'You have quited this mode!'
  64.         return    
  65.     print '''\n\n (10).GOOD LUCK,GOOD BYE!\n\n'''

  66.     
  67. def listWord():
  68.     "list the word depend the regex you input,it will work well when you just know less info about the word"
  69.     
  70.     print "\n======List Mode===== '#' to quit this mode=="
  71.     
  72.     firstwd=raw_input("Enter the first byte [a-z] >>> ").strip().lower()

  73.     if firstwd == '':firstwd='\w'
  74.     
  75.     if firstwd == '#':
  76.         print 'You have quited this mode!'
  77.         preturn
  78.     
  79.     if firstwd not in "abcdefghijklmnopqrstuvwxyz'\w'":
  80.         print "Input the right char as the word's beginning...."
  81.         return    

  82.     regex = raw_input("Enter the keywords >>>").strip().lower()
  83.     if regex == '':regex='\w+'
  84.     if regex == '#':
  85.         print 'You have quited this mode!'
  86.         return

  87.     moreV = 0;
  88.     for firstkey in DT.keys():
  89.         if re.match(firstwd,firstkey):
  90.             for secondkey in DT[firstkey]:
  91.                 if re.search(regex,secondkey) or re.search(regex,DT[firstkey][secondkey]):
  92.                          print ' ' * 10,secondkey,' ====> ',DT[firstkey][secondkey],'\n'
  93.                         moreV += 1
  94.                         if moreV >= 10:
  95.                             moreA=raw_input("---More---")
  96.                             moreV=0
  97.                             if moreA == '#':
  98.                                 return
  99.                         

  100. def addWord():
  101.     "add a new word"
  102.     
  103.     print "\n========Add Mode===== '#' to quit this mode=="

  104.     key = raw_input("Enter the word >>> ").strip().lower()

  105.     while key == '':
  106.         key = raw_input("Enter the word >>> ").strip().lower()
  107.     if key == '#':
  108.         print 'You have quited this mode!'
  109.         return
  110.     if key[0] not in "abcdefghijklmnopqrstuvwxyz":
  111.         print "Input a word beginning with [a-z]...."
  112.         return

  113.     
  114.     word = raw_input('Enter the word\'s meaning >>> ').strip()
  115.     while word == '':
  116.         word=raw_input('Enter the word\'s meaning >>>').strip()
  117.     if word == '#':
  118.         print "You have quited this mode!"
  119.         return

  120.     
  121.     dt={}
  122.     dt[key] = word
  123.     newkey = key[0]
  124.     DT[newkey].update(dt)
  125.     addWord()


  126. def queryWord():
  127.     "query a word's meaning"
  128.     
  129.     print "\n=========Query Mode==== '#' to quit this mode"
  130.     
  131.     key = raw_input('Enter the word >>> ').strip().lower()
  132.     while key == '':
  133.         key=raw_input("Enter the word >>> ").strip().lower()
  134.     if key == '#':
  135.         print "You have quited this mode!"
  136.         return
  137.     
  138.     if not DT.has_key(key[0]):
  139.         return

  140.     if key in DT[key[0]]:
  141.         print ' '*10,key,' ==> ',DT[key[0]][key]
  142.     else:
  143.         print ' '*10,' Cannot Find !'

  144. def updateWord():
  145.     "update a old word or add as a new word"
  146.     
  147.     print "\n============Update Mode======= '#' quit this mode=="
  148.     
  149.     key = raw_input("Enter the word >>> ").strip().lower()
  150.     while key == '':
  151.         key=raw_input("Enter the word >>> ").strip().lower()
  152.     if key == '#':
  153.         print 'You have quited the update mode.'
  154.         return
  155.     
  156.     if not DT.has_key(key[0]):
  157.         return
  158.     if key in DT[key[0]]:
  159.         print DT[key[0]][key]
  160.         
  161.         yesno=raw_input("Do you want to update it?[yes][no]")
  162.         if yesno == 'yes':
  163.             word=raw_input("Enter the word\'s new meaning >> ").strip()
  164.             while word == '':
  165.                 word=raw_input("Enter the word\'s new meaning >>> ").strip()
  166.             if word == '#':
  167.                 print 'You have quited this mode!'
  168.                 return
  169.             
  170.             DT[key[0]][key]=word
  171.             print key,' ===New Meaning====> ',word
  172.             
  173.         elif yesno == '#':
  174.             print 'You have quited this mode!'
  175.             return
  176.         else:
  177.             pass

  178.         
  179.     else:
  180.         print ' Can not find the word!'    
  181.     

  182. def saveDT():
  183.     "save the new word into hardisk"
  184.     
  185.     f = open(default_file,'w')
  186.     f.write(str(DT))
  187.     f.close()
  188.     print 'You have save this dictionary'

  189. def setting():
  190.     if not os.path.exists(default_file):
  191.         if os.path.exists(default_file+".backup"):
  192.             os.system("cp "+default_file+".backup"+" "+default_file)
  193.             return
  194.         
  195.         os.system("touch "+default_file)
  196.         temp = {}
  197.         for item in 'abcdefghigklmnopqrstuvwxyz':
  198.             temp[item] = {}
  199.             
  200.         ff = open(default_file,'w')
  201.         ff.write(str(temp))
  202.         ff.close()
  203.         print 'You have made a setting file :\n'+default_file+'\n'

  204.     else:
  205.         if not os.path.exists(default_file+".backup"):
  206.             temp = {}
  207.             for item in 'abcdefghigklmnopqrstuvwxyz':
  208.                 temp[item] = {}
  209.                 
  210.             ff = open(default_file,'w')
  211.             ff.write(str(temp))
  212.             ff.close()
  213.             return
  214.         
  215.         ff = open(default_file,'r')
  216.         if ff.read() == '':
  217.             ff.close()
  218.             os.system("cp "+default_file+".backup "+default_file)
  219.             
  220. def deleteWord():
  221.     "delete a old word"
  222.     
  223.     print "\n=======Delete Mode======= '#' to quit\n\n"
  224.     
  225.     key = raw_input("Enter the word >>> ").strip().lower()
  226.     while key == '':
  227.         key=raw_input("Enter the word >>> ")
  228.     if key == '#':
  229.         print 'You have quited the delete mode'
  230.         return
  231.     
  232.     if not DT.has_key(key[0]):
  233.         print "Can not find it!"
  234.         return
  235.     
  236.     if key in DT[key[0]]:
  237.         print key,' ===> ',DT[key[0]][key]
  238.         yesno = raw_input("Do you want to delete it?[yes][no]").strip().lower()
  239.         if yesno == 'yes':
  240.             print DT[key[0]][key],' ===== Have Deleted===='
  241.             DT[key[0]].pop(key)
  242.         elif yesno == '#':
  243.             print 'You have quited this mode!'
  244.             return
  245.         else:
  246.             pass

  247.         
  248.     else:
  249.         print ' Can not find the word'

  250. def exit():
  251.     "exit the dictionary"
  252.     
  253.     saveDT()
  254.     print ',\n','*' * 80,'\n'
  255.     print ' ' * 20,'GoodBye,Good Luck!',' ' * 10,'\n'
  256.     print '*' * 80,'\n\n'
  257.         

  258. def version():
  259.     "version information"
  260.     
  261.     print '*' * 80
  262.     print '''
  263.         MyDictionary Version 4.2
  264.         Command Line Function Programming
  265.         By ClownFish
  266.         @ 2011-05-05
  267.         Email:pythonisland@gmail.com
  268.         '''
  269.     print '*' * 80

  270. def main():
  271.     "main function for testing"
  272.     
  273.     setting()
  274.     os.system("cp "+default_file+" "+default_file+".backup") # backup dict
  275.     
  276.     f = open(default_file,'r')
  277.     try:
  278.         DT.update(eval(f.read().strip()))    # convert string to dict
  279.     except:
  280.         pass
  281.     
  282.     f.close()

  283.     version()
  284.     
  285.     while True:
  286.         Entry = raw_input('''
  287.                 (A)dd
  288.                 (Q)uary
  289.                 (U)pdate
  290.                 (L)ist
  291.                 (S)ave    
  292.                 (D)elte
  293.                 (H)elp
  294.                 (E)xit
  295.                 (V)ersion
  296.                 ''').strip().lower()
  297.         if Entry in 'aqueldsvh' and Entry != '':
  298.             if Entry == 'a':
  299.                 addWord()
  300.                 saveDT()
  301.             elif Entry == 'q':
  302.                 queryWord()
  303.             elif Entry == 'u':
  304.                 updateWord()
  305.                 saveDT()
  306.             elif Entry == 'l':
  307.                 listWord()
  308.             elif Entry == 'd':
  309.                 deleteWord()
  310.                 saveDT()
  311.             elif Entry == 's':
  312.                 saveDT()
  313.             elif Entry == 'v':
  314.                 version()
  315.             elif Entry == 'h':
  316.                 help()
  317.             else:
  318.                 exit()
  319.                 break
  320.         else:
  321.             pass
  322.         
  323. if __name__ == '__main__':
  324.     default_file = os.path.expanduser('~/.newDT.txt') # convert '~' to homedir
  325.     DT = {}
  326.     main()

阅读(1348) | 评论(2) | 转发(0) |
给主人留下些什么吧!~~

网络安全服务2011-05-26 15:12:37

看晕了```

zhubuntu2011-05-06 16:02:53

好难看的编辑器。。。。