def prtpos(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 find_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_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 = find_line(each_line, key)
key_dict[count] = pos
f.close()
def search_files(key, file_addr):
all_files = os.walk(file_addr)
txt_file = []
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_file.append(each_file)
for each in txt_file:
key_dict = search_file(each, key)
if key_dict:
print('在文件【%s】中找到关键字【%s】'%(each, key))
prtpos(key_dict)
key = input('请输入关键字:')
file_addr = input('请输入地址:')
search_files(key, file_addr)
|