gpt4 book ai didi

python - python 中的正则表达式不正确

转载 作者:太空宇宙 更新时间:2023-11-04 10:38:43 24 4
gpt4 key购买 nike

我想用字母和数字拆分一些行,但我想不出合适的正则表达式。

行的格式类似于 unit = value+unit,一些例子:

width = 3.45cm
height = 2m
width = 2mm
height = 6.67m

我想为每个名称、值和单位获得单独的输出,这就是我所做的:

line = infoData.readline()
names = []
values = []
units = []
while line:

if "=" in line:
names.append(line[0:line.index("=")])
m = re.search('\d+', line[line.index("="):len(line)])
values.append(int(m.group()))
m = re.search('\D+[^=\n\.]', line[line.index("="):len(line)])
units.append(m.group())
line = infoData.readline()

else:
line = infoData.readline()

我唯一以期望的方式获得的是名称....

最佳答案

你把事情复杂化了一点。我会使用:

data = []

for line in infoData:
if '=' not in line:
continue
name, value = line.split('=')
value, unit = re.search('([\d.]+)(\w+)', value).groups()

data.append({'name': name.strip(), 'value': float(value), 'unit': unit})

对于为您提供字典列表的示例数据:

[{'name': 'width', 'unit': 'cm', 'value': 3.45},
{'name': 'height', 'unit': 'm', 'value': 2.0},
{'name': 'width', 'unit': 'mm', 'value': 2.0},
{'name': 'height', 'unit': 'm', 'value': 6.67}]

而不是 3 个单独的列表。

关于python - python 中的正则表达式不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22145278/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com