|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
最后一题,搜索txt文件内关键字符,我自己没做出来,不过按照小甲鱼的答案敲了一遍,不过奇怪的是。。。竟然在一行def的位置报语法错误,但是我详细看了程序,缩进都是统一的,全部用的tab,没用单独用空格的地方。。。。请前辈们帮忙看看。。。谢谢了。。。找错误找了一小时了。。。
报错报在第8行,invaild Syntax
import os
def print_pos(key_dict):
keys=key_dict.keys()
keys=sorted(keys)
for each_key in keys:
print ('keyword is in %s line, %S position'%(each_key,str(key_dict[each_key]))
def pos_in_line(line,key):
pos = []
begin = line.find(key)
while begin != -1:
pos.append(begin + 1) # 用户的角度是从1开始数
begin = line.find(key, begin+1) # 从下一个位置继续查找
return pos
def search_in_file(file_name,key):
f=open(file_name)
count=0
key_dict=dict()
for each_line in f:
count+=1
if key in each_line:
pos = pos_in_line(each_line,key)
key_dict[count]=pos
f.close()
print (key_dict)
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':
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)
if key_dict:
print ('=======================================')
print ('in file %s we found keyword %s'%(each_txt_file,key))
if detail in ['YES','Yes','yes']:
print_pos(key_dict)
print (txt_files)
key=input('please enter the keywords:')
detail=input(('do you want to print out the position in file of %s (yes/no)')%key)
search_files(key,detail)
|
|