import os
#----------打印key在每行中的位置行数是键值,key在该行里的位置是value------
def print_pos(key_dict):
keys=key_dict.keys()
keys=sorted(keys)#字典是无序的对字典排序
for each_key in keys:
print('关键字出现在第%s行,第%s个位置'
%(each_key,key_dict[each_key]))
print(key_dict)
#------------寻找key在每行中的位置----------
def pos_in_line(line,key):
pos=[]
begin=line.find(key)#返回在行中key的位置,没有位置返回-1
while begin!=-1:
pos.append(begin+1)#用户的角度是从1开始数
begin=line.find(key,begin+1)#从下一个位置继续查找
return pos
#----------将行数和该行里面Key的位置存放在字典key_dict里------------
def search_in_file(file_name,key):
f=open(file_name,encoding='utf-8')
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 #将每行中的位置赋给该行数count
f.close()
return key_dict #返回字典(字典中存有行数和该行上的位置)
#-------寻找txt文件--------------------------------------
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) #在txt文件中找key并将结果存在字典中
if key_dict:
print('-----------------------------------------')
print('在文件%s中找到关键字%s'%(each_txt_file,key))
if detail in ['y','Y']:
print_pos(key_dict)
key=input('请将该脚本防御待查找的文件内,请输入关键字;')
detail=input('是否需打印关键字%s在文件中的位置(y/n):'%key)
search_files(key,detail)