Это более общий и многократно используемый, я считаю:
import re
def tuple_producer(input_lines, attributes):
"""Extract specific attributes from lines 'blabla attribute=value …'"""
for line in input_lines:
line_attributes= {}
for match in re.finditer("(\w+)=(\d+)", line):
line_attributes[match.group(1)]= int(match.group(2)) # int cast
yield tuple(
line_attributes.get(attribute, 0) # int constant
for attribute in wanted_attributes)
>>> lines= """blablabla checked=12 unchecked=1
blablabla unchecked=13
blablabla checked=14""".split("\n")
>>> list(tuple_producer(lines, ("checked", "unchecked")))
[(12, 1), (0, 13), (14, 0)]
# and an irrelevant example
>>> list(tuple_producer(lines, ("checked", "inexistant")))
[(12, 0), (0, 0), (14, 0)]
Обратите внимание на преобразование в целое число; если это нежелательно, удалите кастинг int
, а также конвертируйте константу 0
int в "0"
.