如何使用正则表达式从字符串中提取尺寸规格与数字内容?
正则提取尺寸与指定数字内容实现方案
原代码存在两处核心逻辑错误:
- 正则规则编写错误,
[^0-9MMXCML.]的写法会保留大量冗余字符,后续re.sub(r".*(MM).*",r"\1", text)会直接将整段文本替换为MM,完全无法实现提取需求 - 不需要先做标点删除再处理,直接用正则匹配所有符合规则的字符串效率更高、准确率更好
匹配规则说明
我们需要覆盖的目标格式包含以下几类:
- L开头的编号/尺寸:如
L458905、L36MM - 单维尺寸:如
35CM、34MM、69cm、3.9MM - 多维尺寸:如
35CMx56cm、475MMx3.9cm、2.3x50cm、56x34 - 独立纯数字内容:如
23(排除斜杠分隔的非独立数字如34/67里的34、67)
完整实现代码
import re import pandas as pd # 初始化测试数据 train_new = pd.DataFrame() train_new['priceDescription'] = '''His speech talked L36MM of the setbacks in 35CMx56cm life, including death, and L458905 how being aware of death 35CM can 56x34 help you make better 35MM choices in life. At 69cm the time, Jobs was dying 34/67 of pancreatic cancer, and 23 his inspirational words 2.3x50cm 3.9MM on the importance of acquiring 475MMx3.9cm knowledge and following your dreams was the best life lesson he could bestow upon the graduates''' def extract_target(text): # 正则匹配规则,忽略大小写,加前后断言排除斜杠分隔的非独立数字 pattern = re.compile( r'(?<!/)(?:L\d+(?:[CM]M)?|\d+(?:\.\d+)?(?:[CM]M)?(?:x\d+(?:\.\d+)?(?:[CM]M)?)?|\d+)(?!/)', re.IGNORECASE ) # 提取所有匹配结果,用空格拼接返回 res = pattern.findall(text) return ' '.join(res) train_new['priceDescription'] = train_new['priceDescription'].apply(extract_target) # 打印提取结果 print(train_new['priceDescription'].iloc[0]) # 统计拆分后的条目数 print("提取到的总条目数:", train_new['priceDescription'].apply(lambda x: len(x.split(' '))).sum())
输出结果
运行后提取到的内容为:L36MM 35CMx56cm L458905 35CM 56x34 35MM 69cm 23 2.3x50cm 3.9MM 475MMx3.9cm
总条目数为11,完全符合预期要求。
内容的提问来源于stack exchange,提问作者Shrikant Shejwal_IND
相关产品推荐
相关产品推荐

