|
发表于 2020-5-13 13:48:51
|
显示全部楼层
看代码时,不是从头到尾看的,一般按代码的执行顺序来看,即先看执行语句,然后看被调用的函数(有主到次,先看输入,输出,实现了什么功能,再具体看每行代码做了什么)。
- import os
- def print_pos(key_dict):
- keys = key_dict.keys() # key_dict是在def search_files里定义,在def search_in_file中被赋值了
- keys = sorted(keys) # 我们假设key在了第一行,第1个字符和第2行,第2个字符处,那么key_dict={1:1,2:2}或者{2:2,1:1}都有可能,因为字典是无序的,所以这里对key进行排序
- for each_key in keys: # 遍历排序改过后的key,按顺序输出关键字在第X行,第X个位置,有多少个关键字,这句话就输出多少次
- print('关键字出现在第 %s 行,第 %s 个位置。' % (each_key, str(key_dict[each_key])))
- def pos_in_line(line, key):
- pos = []
- begin = line.find(key)
- while begin != -1:
- pos.append(begin + 1) # 用户的角度是从1开始数
- begin = line.find(key, begin+1) # 从下一个位置继续查找
- return pos
- def search_in_file(file_name, key):
- f = open(file_name) #打开文件,我更喜欢用with open() as f
- count = 0 # 记录行数
- key_dict = dict() # 字典,用户存放key所在具体行数对应具体位置
-
- for each_line in f: #遍历每行查找有没有key,如果有记录下行数和位置,存到字典key_dict
- count += 1
- if key in each_line:
- pos = pos_in_line(each_line, key) # key在每行对应的位置
- key_dict[count] = pos
-
- f.close()
- return key_dict # 返回key_dict到函数def search_files中
- def search_files(key, detail):
- all_files = os.walk(os.getcwd()) #遍历当前目录,输出为,generator object walk。建议加些print步骤,更直观了解该对象的内容
- txt_files = [] #定义一个空列表,用来存放每个文件的绝对路径
- for i in all_files: # 拿到generator object walk中的内容
- for each_file in i[2]: #i[0]为文件夹路径,i[1]为子文件夹列表,这里只遍历一层的文件,所以直接用i[2]
- if os.path.splitext(each_file)[1] == '.txt': # 根据后缀判断是否文本文件,我更喜欢用if each_file.endswith('.txt')
- 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) #转到def search_in_file
- if key_dict: #如果key_dict不为空
- print('================================================================')
- print('在文件【%s】中找到关键字【%s】' % (each_txt_file, key))
- if detail in ['YES', 'Yes', 'yes']: # 如果最开始输入了想要打印关键字。我更喜欢用if detail.lower()=='yes'
- print_pos(key_dict)
- # 从最后的执行语句看起
- key = input('请将该脚本放于待查找的文件夹内,请输入关键字:')
- detail = input('请问是否需要打印关键字【%s】在文件中的具体位置(YES/NO):' % key)
- search_files(key, detail) #使用了search_files函数,那么回上去看def search_files
复制代码 |
|