|
发表于 2020-2-8 14:11:14
|
显示全部楼层
这样试试:
- """
- 编写一个程序,用户输入关键之,查找当前文件夹内(如果当前文件夹内包含文件夹,泽而进入文件夹继续搜索)
- 所有含有该关键字的文本文件(.txt后缀),要求显示该文件所在的位置及关键字在文件中的具体位置
- (第几行第几列)
- """
- import os
- def print_pos(key_dict): # 输出位置行数的函数
- keys = key_dict.keys() # 将字典的key赋值给keys(代表行数)那value就是代表下标啦
- 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) # 如果行存在就返回该位置的下标(不存在返回-1
- while begin != -1:
- pos.append(begin + 1) # 从用户角度,从1开始
- begin = line.find(key, begin + 1) # 从下一个位置开始(begin)寻找到结束(end)
- return pos # 返回列表(存在关键字的函数)
- def search_in_file(file_name, key): # 打开文件,查看行内是否有关键字,并将其位置存进字典
- f = open(file_name, 'r', encoding="utf-8")
- count = 0 # 用来记录行数
- key_dict = dict() # 字典,用户存放key所在具体行数对应具体位置
- for each_line in f.readlines(): # 逐行寻找
- count += 1
- if key in each_line:
- pos = pos_in_line(each_line, key) # key在每行对应的位置(调用函数2)
- key_dict[count] = pos # 无序的,因为字典内是无序的
- f.close()
- return key_dict # 返回字典
- def search_files(key, detail):
- all_files = os.walk(os.getcwd())
- # 用walk()来返回得到一个三元tupple(dirpath, dirnames, filenames),
- # 来返回路径,目录名,文件名 ???有点不太完全理解
- txt_files = [] # 用列表来建立
- for i in all_files: # 在三元中寻找
- for each_file in i[2]: # 在文件名中寻找后缀是否是.txt
- if os.path.splitext(each_file)[1] == '.txt':
- each_file = os.path.join(i[0], each_file) # 合成路径
- txt_files.append(each_file) # 加进列表
- for each_txt_file in txt_files: # 在.txt中寻找关键字
- 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', 'yes']:
- print_pos(key_dict) # 引用函数,打印位置
- key = input('请将该脚本放于待查找的文件加内,请输入关键字:')
- detail = input('请问是否需要打印关键字【%s】在文件中得到具体位置(yes/no):' % key)
- search_files(key, detail)
复制代码 |
|