【发布时间】:2021-12-27 09:40:56
【问题描述】:
我在下面有一个多行字符串示例,它具有类似表格的结构。我必须解析该结构并将其转换回键值对,以便键是列标题,值是该行的值。我使用了一个正则表达式,但它不能正常工作/
PFB 字符串:
Number of Critical alarms: 0
Number of Major alarms: 0
Number of Minor alarms: 0
Slot Sensor Current State Reading Threshold(Minor,Major,Critical,Shutdown)
---------- -------------- --------------- ------------ ---------------------------------------
P0 PEM Iout Normal 5 A na
P0 PEM Vout Normal 12 V DC na
P0 PEM Vin Normal 242 V AC na
P0 Temp: PEM In Normal 34 Celsius (80 ,90 ,95 ,100)(Celsius)
P0 Temp: PEM Out Normal 30 Celsius (80 ,90 ,95 ,100)(Celsius)
R0 Temp: FC FANS Fan Speed 60% 23 Celsius (25 ,35 ,0 )(Celsius)
P0 Temp: FC FAN0 Fan Speed 60% 23 Celsius (25 ,35 ,0 )(Celsius)
P1 Temp: FC FAN1 Fan Speed 60% 23 Celsius (25 ,35 ,0 )(Celsius)
预期输出:
[{'Slot': 'P0', 'Sensor': 'PEM Iout', 'Current State': 'Normal', 'Reading': '5 A', 'Threshold': 'na'}, ...]
我使用了以下正则表达式模式:
r'^(?P<Slot>[^\s]+)[ \t]+(?P<Sensor>[a-zA-Z0-9:]+ [a-z0-9A-Z.:-]* [a-z0-9]*)[ \t]+(?P<State>[a-zA-Z]*)[ \t]+'
【问题讨论】:
-
取每一行并用
\s{3,}分割-见a demo on regex101.com。 -
@Jan 我相信这会拆分同一列的
5 A... -
列的宽度是否始终相同?