python第30讲第4题
importosdef print_pos(key_dict):
keys = key_dict.keys()
keys = sorted(keys)
for each_key in keys:
print('关键字出现在第%s行,第%s个位置。' % (each_key,str(key_dict)))
def pos_in_lin(line,key):
pos = []
begin = line.find(key)
while begin != -1:
pos.append(begin + 1) #用户的角度是从1开始数,而python是从0开始数
begin = line.find(key,begin+1) #从下一个位置继续查找
return pos
def search_in_file(file_name,key):
f = open(file_name)
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 = pos
f.close()
returnkey_dict
def search_files(key,detail):
all_files = os.walk(os.getcwd())
txt_files = []
for i in all_files:
for each_file in i:
if os.path.splitext(each_file) == '.txt': #根据后缀判断是否文本文件
each_file = os.path.join(i,each_file)
txt_files.append(each_file)
for each_txt_file in txt_files:
key_dict = search_files(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('请将该脚本放于带查找的文件夹内,输入关键字:')
detail = input('请问是否需要打印关键字【%s】在文件中的具体位置(YES/NO:' % key)
search_files(key,detail)
运行起来语法报错 在 if detail in ['YES','Yes','yes']:的冒号显示红色,按理应该没问题,没发现bug在哪{:10_324:} 用了中文标点吧
把冒号改成英文的
如果有帮助,请设最佳答案{:10_254:} 49行尾少括号
50行尾应该是英文冒号。 这一句用枚举很被动
if detail in ['YES','Yes','yes'] :
字符串忽略大小写比较就好了
if detail . lower() in ['yes']:
你的print('在文件【%s】中找到关键字【%s】' % (each_txt_file,key)少了半边括号
页:
[1]