import os
def print_pos(dict1):
keys=dict1.keys()
keys=sorted(keys)
for each in keys:
print('关键字出现在%s行,%s个位置'% (each,str(dict1[each])))
def line_pos(each_line,key):
pos=[]
begin=each_line.find(key)
while begin != -1:
pos.append(begin+1)
begin=each_line.find(key,begin+1)
return pos
def file_line(each_file1,key):
f=open(each_file1)
count=0
dict1=dict()
for each_line in f:
count+=1
if key in each_line:
pos=line_pos(each_line,key)
dict1[count]=pos
f.close()
return dict1
for each_file in all_files:
for i in each_file[2]:
if '.txt' in i:
temp1=os.path.join(each_file[0],i)
list_file.append(temp1)
for each_file1 in list_file:
a=file_line(each_file1,key)
if a:
print('===============================================================')
print('在文件%s中,找到关键词%s'% (each_file1,key))
print_pos(dict1) #是这里出错了吗?
为什么返回
Traceback (most recent call last):
File "C:/Users/杜一鸣/Desktop/temp.py", line 49, in <module>
search_file(start_dir,key)
File "C:/Users/杜一鸣/Desktop/temp.py", line 44, in search_file
print(dict1)
NameError: global name 'dict1' is not defined
请大神们帮看看,哪里错了,我分明定义过dict1了,谢谢!