正则表达式以匹配条目的变量列表
Regex to match variable list of entries
我正在尝试了解我如何能够制作一个正则表达式模式来匹配已经有点像字典的可变长度的稀疏值列表。
输入字符串的格式为:
log = """
My sensors:
Sensor 0: 11.000 °C
Sensor 1: 12.000 °C
Sensor 2: 13.250 °C
"""
log = """
My sensors:
Sensor 1: 14.375 °C
Sensor 3: 15.625 °C
"""
所以我想要的输出是:
{
0: 11.000,
1: 12.000,
2: 13.250
}
和
{
1: 14.375,
3: 15.625
}
我能得到的最接近的结果是在我遍历日志行时合理地解析单个传感器行:
import re
d = {}
pattern = "[\S\s]*Sensor (?P<sensor_index>\d+): (?P<value>\d+\.\d+) °C[\S\s]*"
for line in log:
match = re.findall(pattern, line)
if match:
matches = match.groupdict()
d[matches['sensor_index']] = matches['value']
print(d)
无需解析整串。将其分成几行并分别解析每一行:
lines = [re.findall("Sensor (\d+):\s+(\d+\.\d+) °C", line)
for line in log.split("\n")]
d = {int(pair[0][0]): float(pair[0][1])
for pair in lines if pair}
#{0: 11.0, 1: 12.0, 2: 13.25}
我正在尝试了解我如何能够制作一个正则表达式模式来匹配已经有点像字典的可变长度的稀疏值列表。
输入字符串的格式为:
log = """
My sensors:
Sensor 0: 11.000 °C
Sensor 1: 12.000 °C
Sensor 2: 13.250 °C
"""
log = """
My sensors:
Sensor 1: 14.375 °C
Sensor 3: 15.625 °C
"""
所以我想要的输出是:
{
0: 11.000,
1: 12.000,
2: 13.250
}
和
{
1: 14.375,
3: 15.625
}
我能得到的最接近的结果是在我遍历日志行时合理地解析单个传感器行:
import re
d = {}
pattern = "[\S\s]*Sensor (?P<sensor_index>\d+): (?P<value>\d+\.\d+) °C[\S\s]*"
for line in log:
match = re.findall(pattern, line)
if match:
matches = match.groupdict()
d[matches['sensor_index']] = matches['value']
print(d)
无需解析整串。将其分成几行并分别解析每一行:
lines = [re.findall("Sensor (\d+):\s+(\d+\.\d+) °C", line)
for line in log.split("\n")]
d = {int(pair[0][0]): float(pair[0][1])
for pair in lines if pair}
#{0: 11.0, 1: 12.0, 2: 13.25}