|
|
发表于 2016-12-12 08:59:03
|
显示全部楼层
- import os
- def print_pos(key_dict): #定义输出函数
- keys = key_dict.keys() #将字典中的key赋值给keys
- keys = sorted(keys) #因为字典中没有排序,需要给字典排序
- for each_key in keys: #遍历序列输出字典中的值
- print('关键字出现在第%s行,第%s个位置'%(each_key,str(key_dict[each_key])))
- def pos_in_line(line,key): #定义每一行的关键字的位置函数
- pos = [] #定义一个空列表用于存放每一行关键字所在的位置
- begin = line.find(key) #有关键字的位置返回给begin,如不存在则返回-1
- while begin != -1:
- pos.append(begin + 1) #若关键字存在将位置数返回到pos列表中,因为程序是从0开始计算的,所以此处应加1
- begin = line.find(key, begin+1) #然后再从begin+1的位置继续寻找关键字
- return pos #返回返回位置列表
- def search_in_file(file_name,key): #定义函数
- f = open(file_name) #打开文件
- key_dict = dict() #定义一个空字典key用来存放第几行出现关键字
- count = 0 #给count一个初始值
-
- for each_line in f: #遍历文件
- count +=1 #每遍历一行count数加1
- if key in each_line: #如果该行中有关键字调用pos_in_line函数
- pos = pos_in_line(each_line,key)
- key_dict[count] = pos #将行数做为key,具体位置作为xalue
- f.close() #关闭文件,返回字典
- return key_dict
- def search_files(key,detail): #定义函数
- all_files = os.walk(os.getcwd()) #返回当前目录的所有子目录
- txt_files = [] #定义列表用于存放文件
- for i in all_files: #遍历all_files
- for each_file in i[2]: #遍历所有包含文件
- if os.path.splitext(each_file)[1] == '.txt': #如果文件是.txt文件结尾的,each_file就是当前路径加文件名
- each_file = os.path.join(i[0],each_file)
- txt_files.append(each_file) #将文件名放到列表中
- for each_txt_file in txt_files: #遍历文件
- key_dict = search_in_file(each_txt_file,key) #调用函数
- if key_dict: #如果文件中有关键字输出
- print('======================================================================')
- print('在文件【%s】中找到关键字【%s】'%(each_txt_file,key))
- if detail in ['YES','Yes','yes']: #如果detail是YES,yes或是Yes中的任意个
- print_pos(key_dict) #调用输出函数
- key = input('请将该脚本放于待查找的文件夹中,请输入关键字:')
- detail = input('请问是否要打印关键字【%s】在文件中的具体位置(YES/NO):'% key)
- search_files(key,detail)
复制代码 |
|