使用python通过split从image name获取文本

2024-04-20 04:27:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个图像,我用image_slicer将图像分成16个切片,这些图像被命名为0804220001-5_01_01.png,0804220001-5_01_02.png,0804220001-5_01_03.png,依此类推。使用split我需要文本01\u01,01\u02,。。 我试过使用split和rsplit,但是没有得到结果。下面是我的代码。你知道吗

#img1 is the path of the image which is 
#Features/input/0804220001-5_02_04.png
name1 = img1.split('/')[-1]
patch = name1.rsplit('_')[1]
print(patch)

我得到的输出是01,但我需要输出是01\u 01,01\u 02


Tags: the图像image文本pngis切片命名
3条回答

可以将re.search_(.*)\.模式一起使用:

import re

str = " 0804220001-5_02_04.png "
print(re.search('_(.*)\.', str).group(1))

它提取02_04作为输出。你知道吗

我们可以在这里尝试使用re.findall作为regex方法:

images = ["0804220001-5_01_01.png", "0804220001-5_01_02.png", "0804220001-5_01_03.png"]
# form single | delimeted string of all images
all_images = "|".join(images)
terms = re.findall(r'(\d+_\d+)\.png', all_images)
print(terms)

这张照片:

['01_01', '01_02', '01_03']
import os

foo = 'some/path/0804220001-5_01_01.png'
print('_'.join(os.path.splitext(foo)[-2].split('_')[-2:]))

输出

01_01

当然你可以把它变成一个函数

相关问题 更多 >