是否有用于从文本中查找和提取字符串的正则表达式

2024-10-03 19:31:11 发布

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

我有一个存储在文本文件中的路径列表。我试图使用正则表达式从本文中提取完整路径

文本文件数据

/IVTP/DB_db/0171-0_7-296&519_510&586-501&586_296&585_305&519_510&520-0_9_25_31_33_33_32-205-35.jpg 
/IVTP/DB_db/0069-0_2-450&447_581&491-579&491_450&490_452&447_581&448-0_0_9_29_17_24_30-209-15.jpg 
/IVTP/DB_base/0395-4_7-175&502_475&612-456&612_175&590_194&502_475&524-10_0_9_14_26_27_27-206-22.jpg 
/IVTP/DB_base/0234-7_21-271&499_461&602-461&602_291&580_271&499_441&521-0_0_1_32_31_31_18-215-37.jpg 
/IVTP/DB_cc/0291-0_7-271&483_527&578-517&574_271&578_281&487_527&483-0_0_20_29_33_26_18-212-93.jpg 
/IVTP/DB_cc/0325-1_6-227&475_507&572-499&565_227&572_235&482_507&475-0_0_23_28_33_25_33-212-30.jpg

我以文本形式读取文件

imgs_abs_path = [line.strip() for line in open('/home/img_data.txt', 'r') if line.strip() != '']
#converting the list to string 
imgs_paths_to_str = ",".join(str(x) for x in imgs_data_abs_path)
# lis the images from the dataset
imgs_data = [f for f in os.listdir('.') if f.endswith('.jpg')]

我的问题

读取每个图像后,我想使用正则表达式检查文本文件中是否存在该名称。如果是,那么我想从文本文件中提取绝对路径

I used this regular expression but it always return empty "(/IVTP/*"+img+")"

我的代码

new_list = []
for img in imgs_data:
   if search(img, imgs_paths_to_str):
       regex = "(/IVTP/*"+img+")"
       new_list.append(re.findall(regex, imgs_paths_to_str))

print(print(new_list))
[]

Tags: thetoinimgfordbdataif
1条回答
网友
1楼 · 发布于 2024-10-03 19:31:11

我建议将文本文件中的路径添加到imgs_paths_to_str列表,而不是字符串,然后重新检查当前目录中找到的文件,只保留那些以所需前缀开头、以目录中找到的文件名结尾的文件:

imgs_paths_to_str = []

with open('/home/img_data.txt', 'r') as f:
    for line in f:
        line = line.strip()
        if line:
            imgs_paths_to_str.append(line)

imgs_data = [f for f in os.listdir('.') if f.endswith('.jpg')]

new_list = []
for img in imgs_data:
    for ipts in imgs_paths_to_str:
        if ipts.startswith('/IVTP/') and ipts.endswith(img):
            print(ipts) # new_list.append(ipts)

Python demo

相关问题 更多 >