python图片文件名排序,并按照规则打上多个标签,生成txt文件

import re
def myc(string):
    p = re.compile("\d+")
    return int(p.findall(string)[0])
import re
def mykey(string):
    p = re.compile("\d+") #\d 是转数字 +是多个数字
    return int(p.findall(string)[1])


img_all=[]
filename = os.listdir(r"D:\Work\process\try\polyu\\")
# with open("new_output_train.txt", "w+") as fp:
for img in filename:
    img_all.append(img.strip())
    img_all.sort(key = myc)
    img_all.sort(key = mykey)
with open("new_output_train1.txt", "w+") as fp:   
    for image in img_all:
        for i in range(26):
            name = "_p" + str(i + 1) +"_"
            if image.find(name) != -1:
                namelabel = i + 1
                newname = "polyu\\"+ "p"+str(namelabel) +"\\"+str(image) + " " + str(namelabel) + " "+ image.split("_")[0].split("s")[1]+'\n'
                fp.write(newname)
        


目标是按照P后面排序,在按照S后面排序,并打上相应的标签
结果:polyu\p1\s28_p1_c3.jpg 1 28
polyu\p1\s29_p1_c1.jpg 1 29
polyu\p1\s29_p1_c3.jpg 1 29
polyu\p1\s30_p1_c1.jpg 1 30
polyu\p1\s30_p1_c3.jpg 1 30
polyu\p2\s7_p2_c1.jpg 2 7
polyu\p2\s7_p2_c3.jpg 2 7
polyu\p2\s8_p2_c1.jpg 2 8
polyu\p2\s8_p2_c3.jpg 2 8
polyu\p2\s9_p2_c1.jpg 2 9

猜你喜欢

转载自blog.csdn.net/qq_38640439/article/details/81093501