python中的正则表达式不正确

2024-09-24 22:29:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着用字母和数字来拆分一些行,但是我不能想出合适的正则表达式。你知道吗

行的格式类似于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()

我唯一想要的就是名字。。。。你知道吗


Tags: researchreadlineindexlennameslinegroup
2条回答

你把事情搞得太复杂了。我会用:

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个单独的列表。你知道吗

data = ["width = 3.45cm","height = 2m","width = 2mm","height = 6.67m","nope"]

import re
pattern = re.compile("(\w+)\s*=\s*([\d.]+)\s*(\w+)")
print [pattern.search(items).groups() for items in data if pattern.search(items)]
# [('width', '3.45', 'cm'), ('height', '2', 'm'), ('width', '2', 'mm'),
#  ('height', '6.67', 'm')]

正则表达式演示:

Regular expression visualization

Debuggex Demo

编辑:如果您正在寻找从正则表达式中获取词典的方法,可以这样做

import re
patt = re.compile("(?P<name>\w+)\s*=\s*(?P<value>[\d.]+)\s*(?P<unit>\w+)")
print [patt.search(items).groupdict() for items in data if patt.search(items)]

输出

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

相关问题 更多 >