Skip to main content
 首页 » 编程设计

python之使用正则表达式提取列表中的部分字符串

2025年05月04日19findumars

如标题所述,我正在尝试使用正则表达式来提取列表中的字符串的一部分。 该列表包含多个字符串,如下所示:

 "[Decoded(data=b'FF01664817', rect=Rect(left=132, top=207, width=171,height=1))]",  
 "[Decoded(data=b'FF01664833', rect=Rect(left=227, top=128, width=-6, height=175))]" 

对于一些上下文,字符串是我使用 cv2 解码的数据矩阵。我想要的是得到 ‘ ’(数据矩阵内容)之间的部分,没有其余部分。

我的方法是这样的:

Data=[re.match(r"\'.*'\)",x[0]) for x in Data] 

但当我打印我的数据时,它只为列表中的每个字符串返回 "Null"。

其余代码

import cv2 
import numpy as np 
import ctypes   
from pylibdmtx.pylibdmtx import decode 
import csv 
import re 
 
img = cv2.imread('C:/Users/ML/Desktop/DataMatrix/Test2.jpg') 
img2 = img 
 
height, width, channels = img.shape 
 
CROP_W_SIZE  = 8  
CROP_H_SIZE = 6 
 
Data = [] 
 
for ih in range(CROP_H_SIZE ): 
    for iw in range(CROP_W_SIZE ): 
 
        x = int(width / CROP_W_SIZE * iw) 
        y = int(height / CROP_H_SIZE * ih) 
        h = int((height / CROP_H_SIZE)) 
        w = int((width / CROP_W_SIZE )) 
       # print(x,y,h,w) 
 
        img = img[y:y+h, x:x+w] 
 
        Name = str(time.time())  
        cv2.imwrite("C:/Users/ML/Desktop/DataMatrix/CROP/" + 'Crop' + str(x+y) +  ".jpg",img) 
        img = img2 
 
        Data.append(str(decode(cv2.imread('C:/Users/ML/Desktop/DataMatrix/CROP/'+ 'Crop' + str(x+y) +'.jpg')))) 
 
Data=[re.match(r"\'.*'\)",x[0]) for x in Data] 
print(Data) 

请您参考如下方法:

这非常脆弱,可能会因看起来不像您的数据而严重崩溃,但是...

import re 
 
 
def parse_key_value(s): 
    return { 
        m.group(1): m.group(2) or m.group(3) 
        for m in re.finditer( 
            r"([a-z]+)=(?:b\'(.+?)\'|(-?\d+?))[,)]", s 
        ) 
    } 
 
 
for x in [ 
    "[Decoded(data=b'FF01664817', rect=Rect(left=132, top=207, width=171, height=1))]", 
    "[Decoded(data=b'FF01664833', rect=Rect(left=227, top=128, width=-6, height=175))]", 
]: 
    print(parse_key_value(x)) 
 

输出

{'data': 'FF01664817', 'left': '132', 'top': '207', 'width': '171', 'height': '1'} 
{'data': 'FF01664833', 'left': '227', 'top': '128', 'width': '-6', 'height': '175'}