【发布时间】:2023-05-14 03:05:01
【问题描述】:
我正在尝试在两个分隔符之间提取一些单词。它适用于脚本找到这些分隔符的文件,但对于其他文件,代码会提取所有文件。
例子:
文件00.txt:
'bqukfkb saved qshfqs illjQNqdj iohqsijqsd qsoiqsdqs'
文件01.txt:
'jkhjkl dbdqs ihnzqid Bad value okkkk SPAN sfsdf didjsfsdf'
我想打开 2 个或更多像这两个这样的文件,并且只提取以下之间的单词: “坏值”和“SPAN”。
我的代码适用于文件 01.txt,但不适用于 00.txt(我认为这是因为它没有找到分隔符,所以他打印了所有内容。我该如何修复它?
def get_path(): #return the path of the selected file(s)
root = Tk()
i= datetime.datetime.now()
day = i.day
month=i.month
root.filename = filedialog.askopenfilenames(initialdir = "Z:\SGI\SYNCBBG",title = "Select your files",filetypes = (("Fichier 1","f6365tscf.SCD*"+str(month)+str(day)+".1"),("all files",".*")))
root.withdraw()
return (root.filename)
def extraction_error(file):
f=open(file,'r')
file=f.read()
f.close()
start = file.find('Bad value') +9
end = file.find('SPAN', start)
return(file[start:end])
paths=get_path()
cpt=len(paths)
for x in range(0,cpt):
print(extraction_error(paths[x]))
Output : saved qshfqs illjQNqdj iohqsijqsd qsoiqsdq
okkkk
所以在这种情况下,我只想提取“okkkk”,而不是为其他文件打印“已保存....”。
提前感谢您的帮助
【问题讨论】: