查找目录下的关键字以及显示行数

 1 import os
 2 def print_pos(key_dict):
 3     keys = key_dict.keys()
 4     keys = sorted(keys) # 由于字典是无序的,我们这里对行数进行排序
 5     for each_key in keys:
 6         print('关键字出现在第 %s 行,第 %s 个位置。' % (each_key, str(key_dict[each_key])))
 7 
 8 def pos_in_line(line, key):
 9     pos = []
10     begin = line.find(key) #查找关键字在每一行中的位置 赋值给begin
11     while begin != -1:
12         pos.append(begin + 1) # 用户的角度是从1开始数
13         begin = line.find(key, begin+1) # 从下一个位置继续查找
14 
15     return pos
16 
17 def search_in_file(file_name, key):
18     f = open(file_name) #打开文本文件
19     count = 0 # 记录行数
20     key_dict = dict() # 定义字典,用户存放key所在具体行数对应具体位置
21     
22     for each_line in f: #遍历文本文件中的每一行
23         count += 1   #行数记录
24         if key in each_line: #如果关键字在某一行中
25             pos = pos_in_line(each_line, key) # key在每行对应的位置  调用pos_in_line函数 传入这个行 和 关键字
26             key_dict[count] = pos
27     
28     f.close()
29     return key_dict
30 
31 def search_files(key, detail):    #第一步调用search_file函数 把 key, detail 参数传入进去
32     all_files = os.walk(os.getcwd()) #遍历当前目录下的所有文档,返回1目录,2包含路径,3包含文件 将返回的结果赋值给all_files
33     txt_files = [] #定义列表txt_files 
34 
35     for i in all_files: #遍历all_files  注意这里的i为单次遍历的三元组
36         for each_file in i[2]: #遍历三元组的第三个值,即遍历文件,这里的each_file 为单次遍历的文件
37             if os.path.splitext(each_file)[1] == '.txt': # 根据后缀判断是否文本文件
38                 each_file = os.path.join(i[0], each_file) #如果each_file 是文本文件  则将该文件的路径名称以及文件名称结合 并赋值给each_file 
39                 txt_files.append(each_file) #列表txt_files 中追加each_file 此时的each_file为全路径含文件名 列表中追加的文本文件全路径
40 
41     for each_txt_file in txt_files:#在列表txt_file中 遍历所有的文本文件 each_txt_file为单次遍历的文本文件名
42         key_dict = search_in_file(each_txt_file, key)#调用seach_in_file函数,传入单次遍历的文本文件名each_txt_file和用户输入的关键字key
43         if key_dict:
44             print('================================================================')
45             print('在文件【%s】中找到关键字【%s】' % (each_txt_file, key))
46             if detail in ['YES', 'Yes', 'yes']:
47                 print_pos(key_dict)
48 
49 key = input('请将该脚本放于待查找的文件夹内,请输入关键字:') #接受用户输入的关键字 key为用户输入的结果
50 detail = input('请问是否需要打印关键字【%s】在文件中的具体位置(YES/NO):' % key) #请示用户是否打印  detail为请示结果
51 search_files(key, detail) #调用函数search_files 传入关键字 key, detail

 

posted @ 2017-02-13 21:57  道高一尺  阅读(719)  评论(0编辑  收藏  举报