|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
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[eac_key])))
def pos_in_line(line,key):
pos=[]
begin=line.find(key)
while begin!=-1:
pos.append(begin+1)#用户从角度1开始数
begin=line.fing(key,begin+1)#从下一个位置继续查找
return pos
def search_in_file(file_name,key):
f=open(file_name)
count=0#记录行数
key_dict=dict()#字典,用户存放key所在具体行数对应具体位置
key_dict[count]=pos#这个不懂'''
for each_line in f:
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,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':#根据后缀1判断是否文本文件
txt_files.append(each_file)
for each_txtfile 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('请将该脚本放于带查找的文件夹内,请输入关键字L:')
detail=input('请问是否需要打印关键字【%s】再问文件中的具体位置(YES/NO):'%key)
search_files(key,detail)
#key_dict[count]=pos#这个不懂''
# count+1#这里不懂
#each_file=os.path.join(i[0],each_file)#'''这里不懂'[0]不懂
# if detail in ['YES','Yes','yes']:#'''这里不懂'''
#detail=input('请问是否需要打印关键字【%s】再问文件中的的具体位置(YES/NO):'%key)
#这个没有被命名吧!
|
|