首页 > 解决方案 > 从字符串中提取尺寸的正则表达式,例如“2” (7cm) high, 3” (9cm) long and 2” (7cm) wide'

问题描述

我正在尝试从未格式化的字符串描述中提取数据集中项目的物理尺寸。它们在字符串中的表达方式有很多种。这里有些例子:

2” (7cm) high, 3” (9cm) long and 2” (7cm) wide
7” (20cm) high, 5” (15cm) wide and 5” (13cm) deep
4” high, 7” wide and 5” deep
6 inches high, 17 inches wide, and 6 inches deep

我试图以最优雅的方式提取它们,理想情况下,每个维度只使用一个正则表达式,但我似乎无法理解如何去做,我什至不知道从哪里开始,真的。我正在使用 pandas DataFrame 和extract()方法,如果有区别的话。这是我到目前为止所拥有的:

r'(?P<height_cm>\d+)cm\) high'
r'?P<width_cm>\d+)cm\) wide'
r'(?P<length_cm>\d+)cm\) [deep|long]'

但这显然只捕获了厘米数。如果存在,我怎样才能捕获英寸?我怎样才能使用英寸符号或英寸这个词,以便它们都匹配?

任何帮助将不胜感激。

标签: pythonregexpandas

解决方案


以下给出的示例(假设 deep 和 long 是相同的维度):

(?:(?:((?:(?P<height_inch>\d+)(?:”| inches))(?: \((?P<height_cm>\d+)(?:\s?cm)\))? high)|((?:(?P<deep_inch>\d+)(?:”| inches))(?: \((?P<deep_cm>\d+)(?:\s?cm)\))? (?:deep|long))|((?:(?P<wide_inch>\d+)(?:”| inches))(?: \((?P<wide_cm>\d+)(?:\s?cm)\))? wide)).*?)+

编辑:上面的正则表达式更新以使用re.fullmatchSeries.str.extractall

这个可能更容易使用:

((?:(?P<inch>\d+)(?:”| inches))(?: \((?P<cm>\d+)(?:\s?cm)\))? (?P<side>high|wide|deep|long))

也与Series.str.extractall

在正则表达式101


推荐阅读