|
4鱼币
编写一个程序,用户输入关键字,查找当前文件夹内(如果当前文件夹内包含文件夹,则进入文件夹继续搜索)所有含有该关键字的文本文件(.txt后缀),要求显示该文件所在的位置以及关键字在文件中的具体位置(第几行第几个字符),程序实现如图:
import os
def print_pos(key_dict):
keys = key_dict.keys()
keys = sorted(keys)
for each_key in keys:
print("关键字出现在第%行,第%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)
begin = line.find(key,begin+1)
return pos
def search_in_file(file_name,key):
f = open(file_name)
count = 0
key_dict = dict()
for each_line in f:
count += 1
if key in each_line:
pos = pos_in_line(each_line,key)
key_dict[count] = pos
def search_files(key,detail):
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':
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']:
print_pos(key_dict)
key = input('请将该脚本放于待查找的文件内,请输入关键字:')
detail = input('请问是否需要打印关键字【%s】在文件中的具体位置(YES/NO):' % key)
search_files(key,detail)
这是零基础学PYTHON系列第30课后最后一题课后习题,我把测试文件放在了保存该代码文件的同一个文件夹内,运行以后没有结果,这是为什么呢?
帮你改完了,search_in_file 函数忘记返回 key_dict 字典了
而而且 search_in_file 函数 的 key_dict[count] = pos,应该加一个缩进到 if 下
参考代码:import os
def print_pos(key_dict):
keys = key_dict.keys()
keys = sorted(keys)
for each_key in keys:
print("关键字出现在第%d行,第%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)
begin = line.find(key, begin + 1)
return pos
def search_in_file(file_name, key):
f = open(file_name)
count = 0
key_dict = dict()
for each_line in f:
count += 1
if key in each_line:
pos = pos_in_line(each_line, key)
key_dict[count] = pos
return key_dict
def search_files(key, detail):
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':
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']:
print_pos(key_dict)
key = input('请将该脚本放于待查找的文件内,请输入关键字:')
detail = input('请问是否需要打印关键字【%s】在文件中的具体位置(YES/NO):' % key)
search_files(key, detail)
|
最佳答案
查看完整内容
帮你改完了,search_in_file 函数忘记返回 key_dict 字典了
而而且 search_in_file 函数 的 key_dict[count] = pos,应该加一个缩进到 if 下
参考代码:
|