You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python从字符串提取x,y,z坐标并生成指定格式字典

问题:从字符串提取点坐标生成指定格式的字典

我有一个字符串,需要为每个点创建包含x、y、z坐标的dictionary(字典)。

尝试的代码

data= {}

string = "point {x: 0.4921014904975891  y: 0.27571001648902893  z: -0.4787609279155731}point {x: 0.4930153489112854  y: 0.2628157138824463  z: -0.45403242111206055}"

for i in range(len(string)):
      X_var = "X" + str(i)
      Y_var = "Y" + str(i)
      Z_var = "Z" + str(i)

      data[X_var] = float(string.point[i].x)
      data[Y_var] = float(string.point[i].y)
      data[Z_var] = float(string.point[i].z)

期望结果

data = {'X1': 0.4921014904975891, 'Y1': 0.27571001648902893, 'Z1': -0.4787609279155731, 'X2': 0.4930153489112854 , 'Y2': 0.2628157138824463, 'Z2': -0.45403242111206055}

运行错误

AttributeError: 'str' object has no attribute 'point'

请问如何从该字符串中提取所需的坐标值?


解决方案

错误原因

你错误地将字符串对象当作了带有point属性的自定义对象,Python的字符串类型本身没有point属性,因此触发了AttributeError。需要通过字符串解析的方式提取坐标值。

方法一:使用正则表达式(推荐)

正则表达式可以精准匹配每个点的x、y、z数值,代码简洁且适用性强:

import re

data = {}
string = "point {x: 0.4921014904975891  y: 0.27571001648902893  z: -0.4787609279155731}point {x: 0.4930153489112854  y: 0.2628157138824463  z: -0.45403242111206055}"

# 匹配x、y、z后的数值,支持正负小数
pattern = r'x:\s*([\d.-]+)\s*y:\s*([\d.-]+)\s*z:\s*([\d.-]+)'
points = re.findall(pattern, string)

# 遍历匹配结果,填充字典
for idx, (x, y, z) in enumerate(points, start=1):
    data[f'X{idx}'] = float(x)
    data[f'Y{idx}'] = float(y)
    data[f'Z{idx}'] = float(z)

print(data)

方法二:分割字符串后解析

通过分割字符串提取每个点的内容块,再逐个解析坐标:

data = {}
string = "point {x: 0.4921014904975891  y: 0.27571001648902893  z: -0.4787609279155731}point {x: 0.4930153489112854  y: 0.2628157138824463  z: -0.45403242111206055}"

# 分割得到每个point的内容块,过滤空内容并去除结尾的}
point_blocks = [block.rstrip('}') for block in string.split('point {') if block]

# 遍历每个块解析坐标
for idx, block in enumerate(point_blocks, start=1):
    coords = block.split()
    data[f'X{idx}'] = float(coords[1])
    data[f'Y{idx}'] = float(coords[3])
    data[f'Z{idx}'] = float(coords[5])

print(data)

两种方法运行后都能得到你期望的字典结果。


内容的提问来源于stack exchange,提问作者mcdonasd11

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 13:52:49