思路
可以将特定的字符串组成一个txt文档,然后在要查看的字符串中通过遍历这个txt文档进行分类
if mall_strdata in imgname: # 如果字符串mall_strdata在imgname里面
strip()|rstirp()分别从左右执行删除操作。默认情况下会删除空白或者换行符,也可以指定其他字符
#查看特定的字符串是否存在
import os
import os.path as osp
str = "string test string test"
def classify(txt_path,mall_path,store_path,outfile_path):
#通过txt文档得到每一列的信息
storetxt_path = osp.join(outfile_path, 'storeface.txt')
malltxt_path = osp.join(outfile_path, 'mallface.txt')
othertxt_path =osp.join(outfile_path,'otherface.txt')
with open(txt_path,'r') as txt:
data_list = txt.readlines() # 读取全部行
with open(mall_path,'r') as mall_txt:
malldata_list = mall_txt.readlines() # 读取全部行
with open(store_path,'r') as store_txt:
storedata_list = store_txt.readlines() # 读取全部行
storedata = []
malldata = []
otherdata = []
for line in data_list:
linedata = line.strip()
imgname = linedata.split(' ')[0]
label = linedata.split(' ')[1]
flag = 0
for store in storedata_list:
store_strdata =store.strip()
if (store_strdata in imgname): # 如果字符串在imgname里面
storedata.append("{} {}\n".format(imgname, label))
flag = 1
break
if flag == 0:
for mall in malldata_list:
mall_strdata = mall.strip()
if mall_strdata in imgname: # 如果字符串在imgname里面
malldata.append("{} {}\n".format(imgname, label))
flag = 1
# print('mall')
break
if flag == 0:
# print('other')
otherdata.append("{} {}\n".format(imgname, label))
print(len(storedata))
print(len(malldata))
print(len(otherdata))
with open(storetxt_path,'w') as store_txt:
store_txt.writelines(storedata)
with open(malltxt_path, 'w') as mall_txt:
mall_txt.writelines(malldata)
with open(othertxt_path,'w') as other_txt:
other_txt.writelines(otherdata)
#__name__ == '__main__' 就表示在当前文件中,可以在if __name__ == '__main__':条件下写入测试代码,
# 如此可以避免测试代码在模块被导入后执行。
def test():
with open('otherface.txt', 'r') as fp:
data = fp.readlines()
print(len(data))
if __name__ == '__main__':
txt_path = './face.gt.list'
mall_path = './mall.txt'
store_path = './store.txt'
outfile_path = './'
classify(txt_path,mall_path,store_path,outfile_path)
# test()