|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
import os
def search(target,contents):
txt_list = []
os.chdir(contents)
f = os.walk(os.getcwd())
for each in f:
if os.path.splitext(each)[1] == '.txt':
txt_list.append(each)
return txt_list
def position(target,file_name):
line = 0
rank = []
position=dict()
for each in txt_list:
f = open(each)
for eachline in f:
line+=1
begin = eachline.find(target)
while begin != -1:
rank.append(begin+1)
begin = eachline.find(target,begin+1)
position[line]=rank
f.close()
return position
target = input('请将该脚本放于待查找的文件夹内,请输入关键字:')
print('请问是否需要打印关键字【%s】在文件中的具体位置(YES/NO)'%(target),end='')
order = input("")
if order =='YES':
txt_list = search(target,os.curdir)
for each in txt_list:
position = position(target,each)
if position:
line = position.keys()
line = sorted(line)
for each_line in line:
print('============================================================')
print('在文件【%s】中找到关键字【%s】'%(each,target))
print('关键字出现在第%s行,第%s个位置'%(each_line,str(position[each_line])))
运行以后报错
Traceback (most recent call last):
File "C:\Users\lenovo\Desktop\python\搜索文本中关键字副本.py", line 32, in <module>
txt_list = search(target,os.curdir)
File "C:\Users\lenovo\Desktop\python\搜索文本中关键字副本.py", line 7, in search
if os.path.splitext(each)[1] == '.txt':
File "C:\Users\lenovo\AppData\Local\Programs\Python\Python35-32\lib\ntpath.py", line 224, in splitext
return genericpath._splitext(p, '\\', '/', '.')
File "C:\Users\lenovo\AppData\Local\Programs\Python\Python35-32\lib\genericpath.py", line 118, in _splitext
sepIndex = p.rfind(sep)
AttributeError: 'tuple' object has no attribute 'rfind'
求助是怎么回事啊
|
|