import os
def find_word(line,word): #关键字在某一行的具体位置
n = []
m = line.find(word)
while m != -1:
n.append(m)
m = line.find(word,m + 1)
return n
def find_line(file,word): #定义记录关键字行数的函数
n = 0
f = open(file,'rt')
m = {}
for i in f:
n += 1
if word in i:
q = find_word(i,word)
m[n] = q
f.close()
return m
def file_find(paths,word):
text_files = []
all_files = os.walk(paths)
for i in all_files:
for r in i[2]:
if os.path.splitext(r)[1] == '.txt':
r = os.path.join(i[0],r)
text_files.append(r)
for each_text in text_files:
m = find_line(each_text,word)
if m:
print('\n'+f'文件路径:{each_text}'.center(60,'-'))
print_file(m)
def print_file(m): #定义输出函数
for each_keys in m:
print(f'关键字出现在{each_keys}行的第{m[each_keys]}个字符')
word = input('请输入关键字:')
paths = input('请输入查找初始路径:')
file_find(paths,word)
|