- 论坛徽章:
- 0
|
本帖最后由 shaogang428 于 2010-11-06 17:56 编辑
使用下列脚本的搜索功能的时候会提示KeyError,麻烦给我检查下。谢谢。- #coding:gbk
- import sys,cmd
- from cdctools import *
- class PyCDC(cmd.Cmd):
- def __init__(self):
- cmd.Cmd.__init__(self)
- self.cdrom = 'h:\\My Dropbox\\python\\'
- self.dir = 'd:\\Python\\CD2\\'
- self.prompt = "(PyCDC)>"
- self.intro = '''PyCDC0.5 使用说明:
- dir 目录名 #指定保存和搜索目录,默认是 "cdc"
- walk 文件名 #指定光盘信息文件名,使用 "*.cdc"
- find 关键词 #使用在保存和搜索目录中遍历所有.cdc文件,输出含有关键词的行
- ? # 查询
- EOF # 退出系统,也可以使用Crtl+D(Unix)|Ctrl+Z(Dos/Windows)
- '''
- def help_EOF(self):
- print "退出程序,Quit the program"
- def do_EOF(self,line):
- sys_exit()
- def help_walk(self):
- print "扫描文件目录 walkcd and export into *.cdc"
- def do_walk(self,filename):
- if filename == "":filename = raw_input("输入cdc文件名::")
- print "扫描光盘内容保存到:'%s'"% filename
- cdWalker(self.cdrom,self.dir+filename)
- def help_dir(self):
- print "指定保存/搜索目录"
- def do_dir(self,pathname):
- if pathname == "":pathname = raw_input("输入指定保存/搜索目录:")
- self.dir = pathname
- print "指定保存/搜索目录:'%s';默认是:'%s'"%(pathname,self.dir)
- def help_find(self):
- print "搜索关键词"
- def do_find(self,keyword):
- if keyword == "":keyword = raw_input("输入搜索关键词:")
- print "搜索关键词:'%s'"% keyword
- cdcGrep(self.dir,keyword)
- if __name__ == '__main__':
- cdc = PyCDC()
- cdc.cmdloop()
复制代码 下列是调用的cdctools.py- import os
- import pickle
- def cdWalker(cdrom,cdcfile):
- export = ""
- for root,dirs,files in os.walk(cdrom):
- export += "\n %s;%s;%s"% (root,dirs,files)
- open(cdcfile,'w').write(export)
- def cdcGrep(cdcpath,keyword):
- '''光盘信息文本关键词搜索函式
- @note: 使用最简单的内置字串匹配处理来判定是否有关键词包含
- @param cdcpath: 包含*.cdc 文件的目录
- @param keyword: 搜索的关键词
- @return: 组织匹配好的信息到字典中导出成 searched.dump 文件
- @todo: 可结合搜索引擎进行模糊搜索!
- '''
- expDict = {}
- filelist = os.listdir(cdcpath) # 搜索目录中的文件
- cdcpath=cdcpath+"/"
- for cdc in filelist: # 循环文件列表
- if os.path.isdir(cdcpath+cdc):
- cdcGrep(cdcpath+cdc,keyword) # 若是子目录,则递归调用完成查找
- else:
- cdcfile = open(cdcpath+cdc) # 拼合文件路径,并打开文件
- for line in cdcfile.readlines(): # 读取文件每一行,并循环
- if keyword in line: # 判定是否有关键词在行中
- #print line # 打印输出
- expDict[cdc].append(line)
- #print expDict
- pickle.dump(expDict,open("d:\\Python\\CD2\\searched.dump","w"))
复制代码 |
|