|
楼主 |
发表于 2018-6-16 23:00:27
|
显示全部楼层
本帖最后由 myckjx 于 2018-6-16 23:39 编辑
改进版优雅的作业做好了
- import os
- def line(file,word):
- n = 0
- list1 = list()
- list2 = list()
- for h in file:
- list1.append([])
- if word in h:
- list2 = h.split(word)
- x = 0
- for t in range(len(list2)-1):
- x += len(str(list2[t]))
- list1[n].append(x+(t*len(word))+1)
- n += 1
- return list1
- def pri(route,word,i,list1,flag):
- file_dict = dict()
- for j in range(len(list1)):
- if list1[j] != []:
- file_dict.update({j+1:list1[j]})
- if file_dict != {}:
- print('=======================================')
- print('在文件【%s】中找到关键字【%s】'%(route+i,word))
- if flag in ['YES','yes','Y','y']:
- for m in file_dict:
- print('关键字出现在第%d行,第%s个位置' % (m,file_dict[m]))
- def find(route,word,flag):
- list1 = os.listdir(route)
- for i in list1:
- if os.path.isfile(route+i):
- if os.path.splitext(i)[1]=='.txt':
- file = open(route+i,'r')
- list2 = line(file,word)
- pri(route,word,i,list2,flag)
- file.close()
- else:
- find(route+i+'\\',word,flag)
- word = input('请将该代码放于待查找的文件夹内,请输入关键字:')
- flag = input('请问是否打印关键字【%s】在文件中的具体位置(YES/NO):'%word)
- find(os.getcwd()+'\\',word,flag)
复制代码 |
|