Python正则提取文本中多格式带可选单位的2/3维尺寸值方案
Python多格式尺寸信息正则提取实现方案
支持匹配的尺寸格式
- 三维分标单位格式:每个维度单独标注单位,例如
10.5 inches x 5 feet x 2 inches - 二维分标单位格式:每个维度单独标注单位,例如
10 inches x 5 inches - 二维统一单位格式:单位统一标注在尺寸末尾,例如
10 x 5 inches
规则说明:尺寸维度固定为2或3个,每个维度数值可单独标注英寸、英尺类计量单位,也可省略单位。
原有正则的核心问题
- 单位匹配逻辑错误:
inches?feet?的写法要求字符串连续匹配英寸、英尺的字符序列,没有做二选一分支匹配,也未设置单位可选 - 第三维度匹配未做整体可选封装,仅给数值加了可选标记,分隔符
x和单位的匹配逻辑独立,容易出现匹配错位 - 未覆盖末尾统一标注单位的场景,无法识别
10 x 5 inches这类格式
可直接运行的实现代码
import re # 预编译尺寸匹配正则 dim_pattern = re.compile( r""" # 匹配第一个维度数值 (\d+\.?\d*) # 第一个维度可选单位(可自行扩展新单位) \s*(inches?|feet|ft|in)?\s* # 匹配维度分隔符x x\s* # 匹配第二个维度数值 (\d+\.?\d*) # 第二个维度可选单位 \s*(inches?|feet|ft|in)?\s* # 第三维度整体可选匹配块 (?: x\s* (\d+\.?\d*) \s*(inches?|feet|ft|in)?\s* )? # 匹配末尾统一标注的全局单位 (inches?|feet|ft|in)? """, re.IGNORECASE | re.VERBOSE ) def extract_dimensions(text: str): match_results = [] for match_item in dim_pattern.finditer(text): dim_list = [] groups = match_item.groups() # 解析第一维度 val1 = float(groups[0]) unit1 = groups[1] dim_list.append((val1, unit1)) # 解析第二维度 val2 = float(groups[2]) unit2 = groups[3] dim_list.append((val2, unit2)) # 解析第三维度(存在才加入结果) if groups[4]: val3 = float(groups[4]) unit3 = groups[5] dim_list.append((val3, unit3)) # 用末尾全局单位补全所有未标注单位的维度 global_unit = groups[6] if global_unit: for idx in range(len(dim_list)): if not dim_list[idx][1]: dim_list[idx] = (dim_list[idx][0], global_unit) match_results.append(dim_list) return match_results
测试示例
# 测试文本 test_content = """ 10.5 inches x 5 feet x 2 inches 10 inches x 5 inches 10 x 5 inches 3.2 ft x 4in x 6 feet """ print(extract_dimensions(test_content))
返回结果为嵌套列表:每个外层元素对应一处匹配到的尺寸,内层每个元组对应一个维度,格式为
(维度数值, 对应单位),自动补全缺省的单位信息。
自定义调整方法
- 新增支持的计量单位:直接修改正则中所有单位可选分组的分支内容,例如要支持厘米、米,把
(inches?|feet|ft|in)替换为(inches?|feet|ft|in|cm|m)即可 - 正则默认开启大小写忽略,可适配
Inch、FEET这类大小写不规范的书写 - 第三维度采用非捕获分组包裹后设置整体可选,不会出现二维尺寸匹配时的错位、吞字符问题
内容的提问来源于stack exchange,提问作者Vladimir Zaretskiy
相关产品推荐
相关产品推荐

