使用 glob 和 rsplit 获取 png 图像的名称
get the name of a png image using glob and rsplit
我有一组图片如下:
1234_hello_BV56.png
1256_how_5t.png
我想存储在变量中
标签只有'_'
之间的名字
得到 hello
, how
rest_left 1234 1256
休息吧 BV56 5t
总结一下。
对于像 :
这样的输入
1234_hello_BV56.png
我想获得以下内容:
label=你好
rest_left=1234
rest_right=BV56
为此我尝试了以下方法
import os
import glob
os.chdir(path)
images_name = glob.glob("*.png")
先试试
set_img = set([x.rsplit('.', 1)[0] for x in images_name])
它只将整个世界与 png 扩展分开。
第二次尝试
label,sep,rest = img.partition('_')
它returns第一个序列之前'_'
更新:
In [304]: left,labels,right = list(zip(*[os.path.splitext(x)[0].split('_')
for x in images_name]))
In [305]: left
Out[305]: ('1234', '1256')
In [306]: labels
Out[306]: ('hello', 'how')
In [307]: right
Out[307]: ('BV56', '5t')
这是你想要的吗?
In [266]: [os.path.splitext(x)[0].split('_') for x in images_name]
Out[266]: [['1234', 'hello', 'BV56'], ['1256', 'how', '5t']]
我有一组图片如下:
1234_hello_BV56.png
1256_how_5t.png
我想存储在变量中
标签只有'_'
之间的名字
得到 hello
, how
rest_left 1234 1256
休息吧 BV56 5t
总结一下。 对于像 :
这样的输入1234_hello_BV56.png
我想获得以下内容:
label=你好
rest_left=1234
rest_right=BV56
为此我尝试了以下方法
import os
import glob
os.chdir(path)
images_name = glob.glob("*.png")
先试试
set_img = set([x.rsplit('.', 1)[0] for x in images_name])
它只将整个世界与 png 扩展分开。
第二次尝试
label,sep,rest = img.partition('_')
它returns第一个序列之前'_'
更新:
In [304]: left,labels,right = list(zip(*[os.path.splitext(x)[0].split('_')
for x in images_name]))
In [305]: left
Out[305]: ('1234', '1256')
In [306]: labels
Out[306]: ('hello', 'how')
In [307]: right
Out[307]: ('BV56', '5t')
这是你想要的吗?
In [266]: [os.path.splitext(x)[0].split('_') for x in images_name]
Out[266]: [['1234', 'hello', 'BV56'], ['1256', 'how', '5t']]