python - 从字符串中提取尺寸的正则表达式,例如“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]'
但这显然只捕获了厘米数。如果存在,我怎样才能捕获英寸?我怎样才能使用英寸符号或英寸这个词,以便它们都匹配?
任何帮助将不胜感激。
解决方案
以下给出的示例(假设 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.fullmatch
和Series.str.extractall
这个可能更容易使用:
((?:(?P<inch>\d+)(?:”| inches))(?: \((?P<cm>\d+)(?:\s?cm)\))? (?P<side>high|wide|deep|long))
也与Series.str.extractall
推荐阅读
- jquery - jquery modal dialog button div没有右对齐-css使其占据总行
- javascript - VSCode - 如何在 JSDoc 中键入提示 node_modules 类型?
- java - 删除 if 语句和花括号,但保留内容
- python - 熊猫将满足大于和小于条件的列的值倍数
- jenkins-pipeline - 如何使 Jenkins 构建通过或不稳定取决于 Serenity 报告
- python - 如何从 n 个列表中形成所有可能的组合
- java - Spring Boot API 自定义错误响应契约
- mysql - SQL:同时使用 SUM 和 CAST
- node.js - 修改架构后,猫鼬查询挂起
- apache-spark - Spark 的 Dataset 的 limit 函数创建一个只有 1 个分区的新 Dataset。为什么?