|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
题目是这样的
3. 编写一个程序,用户输入关键字,查找当前文件夹内(如果当前文件夹内包含文件夹,则进入文件夹继续搜索)
所有含有该关键字的文本文件(.txt后缀),要求显示该文件所在的位置以及关键字在文件中的具体位置(第几行第几个字符)
答案是这样的
- import os
- def print_pos(key_dict):
- keys = key_dict.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)#str.find(sub,begin,end)字符串查找方法
- 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)
- count = 0#记录关键字出现的行术
- key_dict = dict() #记录key所在具体行数对应具体位置
- for each_line in f:
- count += 1
- if key in each_line:# 这里怎么知道就是一行呢???
- pos = pos_in_line(each_line,key)#key 在每行对应的位置
- key_dict[count] = pos
- f.close()
- return key_dict
- def search_files(key, answer):
- all_files = os.walk(os.getcwd())
- txt_files = []
- for i in all_files:
- for each_file in i[2]:
- if os.path.splitext(each_file)[1] == '.txt': #根据后缀判断是否.txt文件
- 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']:
- print_pos(key_dict)
- key = input("请将该脚本放于待查找的文件夹内,请输入关键字:")
- answer = input("请问是否需要打印关键字【%s】在文件中的具体位置(YES/NO):")
- search_files(key,answer)
复制代码 我的疑问是在函数search_in_line的for each_line in f中怎么知道each_line就是一行呢?
本帖最后由 Twilight6 于 2020-8-23 17:25 编辑
是通过 for 循环遍历文件对象,每次循环文件对象都会读取文件中的一行
用 count 来记录 for 循环读取到文件对象的哪一行
然后当你满足 if 条件时候就进行判断你找的字符是否在这行中就得出结果了
|
|