Is there any regular expression for finding and extract the string from a text

Viewed 91

I have a List of paths stored in a text file. I am trying to extract the full path from this text using a regular expression.

The text file data

/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

I read the file as Text

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')]

My problem

After reading each image, I want to check if the name exists in the text file using a regular expression. If it does, then I want to extract the absolute path from the text file.

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

My code

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))
[]
1 Answers

I suggest adding the paths from the text file into imgs_paths_to_str list, not a string, and then just check agains the files found in the current directory, and only keep those that start with your required prefix and end with the file name found in the directory:

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)

See the Python demo.

Related