|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
import os
key = input('请输入需要查找的关键字:')
choice = input('请问需要打印关键字的位置吗:')
def print_key(key,choice):
for each in os.walk(os.getcwd()):
for i in each[2]:
if os.path.splitext(i)[1] == '.txt':
print(each[0])
file = os.path.join(each[0],i)
print(each[0])
f= open(file)
count = 0
key_dict={}
for each in f:
count +=1
if key in each:
begin = each.find(key)
pos = []
while begin != -1:
pos.append(begin + 1)
begin = each.find(key,begin + 1)
key_dict[count] = pos
if key_dict:
print('===\n在文件【%s】中找到关键字【%s】' % (file,key))
if choice in ['yes','YES','Yes']:
keys = key_dict.keys()
keys = sorted(keys)
for each_key in keys:
print('关键字出现在第%s行,第%s个位置'% (each_key,str(key_dict[each_key])))
print_key(key,choice)
看完答案自己凭记忆由打了一遍,运行时会报错,但自己找不出错误来错误提示以及运行的结果
请输入需要查找的关键字:1
请问需要打印关键字的位置吗:yes
D:\Python32\test
D:\Python32\test
===
在文件【D:\Python32\test\1.txt】中找到关键字【1】
关键字出现在第1行,第[1, 2, 3, 19, 23]个位置
关键字出现在第2行,第[12]个位置
关键字出现在第4行,第[1, 4, 7, 10]个位置
关键字出现在第5行,第[1, 4]个位置
关键字出现在第7行,第[1, 4]个位置
关键字出现在第8行,第[1, 4]个位置
关键字出现在第9行,第[1, 4]个位置
1
1
Traceback (most recent call last):
File "D:\Python32\test\练习2.py", line 34, in <module>
print_key(key,choice)
File "D:\Python32\test\练习2.py", line 15, in print_key
f= open(file)
IOError: [Errno 2] No such file or directory: '1\\12.txt' |
|