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

标签 python regex list

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

文本文件数据

/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))
[]

最佳答案

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

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 .

关于python - 是否有用于从文本中查找和提取字符串的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67564450/

相关文章:

python - 对列表列表进行排序以查找共享变体

java - 空指针错误帮助?

python - 两个文件的 python 'open' 中的模拟

python - 从列表中的字典元组创建字典的字典

Python 2.7 TCP 套接字 : socket. send() 返回零与 socket.send() 引发 socket.error 异常?

.net - 一场比赛后进行多场比赛

R - 删除字符向量中以大写字母开头的字符串

带有字符串索引的 Python 数组

python - 用于精度和召回的 Keras 自定义决策阈值

Javascript:如何提取从index1到index2的单词?