如何使用Python 2.7从字符串中提取3位或6位格式的坐标序列
Python 2.7 坐标提取解决方案
坐标格式说明
项目中需提取两类坐标,规则如下:
- 常规坐标:连续3个数值(支持整数、浮点数、负数),对应x/y/z参数,数值间可使用逗号、空格分隔,逗号前后可带任意空格
- 扩展坐标:连续6个数值(支持整数、浮点数、负数),前3个为位置xyz、后3个为旋转xyz参数,分隔规则同常规坐标
常规坐标示例:
101, 520, 62 960.93 764.22 59.20
扩展坐标示例:
101 520 62 3 0 0 960.93 764.22 59.20 -0.34 0.00 -89.81
测试输入文本
textbefore 101, 520, 62 GOTO 960.93 796.22 59.20 -0.34 0.00 -89.81 $5GOTO 1960.93 1796.22 159.20 -0.34 0.00 -89.81 501, 513, 162 1040, 1040, 520 text after error 222, 222 1500, 1500, 60 (1) 1337 1337 65 124.5, 133.6, 35.4 15:13:26 Condition: index_ != StringList::npos [line 178](125, 157, 215) Allocating shadow map cache 6324 x 6324: 76.28 MB
理想输出结果
101 520 62 960.93 796.22 59.20 -0.34 0.00 -89.81 1960.93 1796.22 159.20 -0.34 0.00 -89.81 501 513 162 1040 1040 520 1500 1500 60 1337 1337 65 124.5 133.6 35.4 125 157 215
实现代码
代码兼容Python 2.7版本,直接运行即可得到上述输出:
import re # 匹配单个数值的正则:支持正负、整数、浮点数 NUM_PAT = r'[-+]?\d*\.?\d+' # 分隔符:逗号(可选前后空格)或空格 SEP_PAT = r'\s*[, ]\s*' # 完整匹配:优先匹配6个连续数值,再匹配3个连续数值,前后避免和其他数字字符粘连 PATTERN = re.compile( r'(?<!\d)(?:{n})(?:{s}{n}){{2}}(?:{s}{n}){{3}}?(?!\d)'.format( n=NUM_PAT, s=SEP_PAT ) ) def extract_coords(text): coords = [] for line in text.splitlines(): matches = PATTERN.findall(line) for match in matches: # 把所有逗号替换成空格,再拆分去重空格,统一用空格分隔 parts = re.split(r'[, ]+', match.strip()) coords.append(' '.join(parts)) return coords if __name__ == '__main__': test_text = """textbefore 101, 520, 62 GOTO 960.93 796.22 59.20 -0.34 0.00 -89.81 $5GOTO 1960.93 1796.22 159.20 -0.34 0.00 -89.81 501, 513, 162 1040, 1040, 520 text after error 222, 222 1500, 1500, 60 (1) 1337 1337 65 124.5, 133.6, 35.4 15:13:26 Condition: index_ != StringList::npos [line 178](125, 157, 215) Allocating shadow map cache 6324 x 6324: 76.28 MB""" result = extract_coords(test_text) for line in result: print(line)
实现说明
- 正则通过
(?<!\d)和(?!\d)环视规则,避免匹配到和其他非坐标数字粘连的内容 - 优先匹配6个数值的扩展坐标,再匹配3个数值的常规坐标,不会出现6个数值被拆成两个3个数值的情况
- 输出统一将分隔符替换为空格,符合要求的输出格式
- 自动过滤只有2个数值的无效行,符合测试用例预期
- 若需允许"Allocating shadow map"行的误识别,可调整正则匹配阈值即可。
内容的提问来源于stack exchange,提问作者holgerm
相关产品推荐
相关产品推荐

