我处于需要解析旧格式的情况。我想做的是编写一个能够识别格式并将其转换为更易于使用的对象的解析器。
我设法解析输入,问题是当我想将它转换回字符串时。总结一下:当我将 my 的结果parse()
作为参数传递给我的compose()
方法时,它不会返回正确的字符串。
这是输出和源代码。我是 peg 的初学者,我有什么误解吗?请注意,我(126000-147600,3);
在我的初始字符串中,而在它-
前面的组合字符串中。
输出:
********************************************************************************
-t gmt+1 -n GB_EN -p '39600-61200,0; (126000-147600,3); -(212400-234000,5); 298800; (320400); 385200-406800,0; 471600-493200,0; 558000-579600,0'
********************************************************************************
gmt+1 GB_EN
********************************************************************************
[{'end': '61200', 'interval': '0', 'start': '39600'},
{'end': '147600', 'interval': '3', 'start': '126000'},
{'end': '234000', 'interval': '5', 'inverted': True, 'start': '212400'},
{'start': '298800'},
{'start': '320400'},
{'end': '406800', 'interval': '0', 'start': '385200'},
{'end': '493200', 'interval': '0', 'start': '471600'},
{'end': '579600', 'interval': '0', 'start': '558000'}]
-t gmt+1 -n GB_EN -p '39600-61200,0; -(126000-147600,3); -(212400-234000,5); 298800; -(320400); 385200-406800,0; 471600-493200,0; 558000-579600,0'
Python源代码:
from pypeg2 import *
from pprint import pprint
Timezone = re.compile(r"(?i)gmt[\+\-]\d")
TimeValue = re.compile(r"[\d]+")
class ObjectSerializerMixin(object):
def get_as_object(self):
obj = {}
for attr in ['start', 'end', 'interval', 'inverted']:
if getattr(self, attr, None):
obj[attr] = getattr(self, attr)
return obj
class TimeFixed(str, ObjectSerializerMixin):
grammar = attr('start', TimeValue)
class TimePeriod(Namespace, ObjectSerializerMixin):
grammar = attr('start', TimeValue), '-', attr('end', TimeValue), ',', attr('interval', TimeValue)
class TimePeriodWrapped(Namespace, ObjectSerializerMixin):
grammar = flag("inverted", '-'), "(", attr('start', TimeValue), '-', attr('end', TimeValue), ',', attr('interval', TimeValue), ")"
class TimeFixedWrapped(Namespace, ObjectSerializerMixin):
grammar = flag("inverted", '-'), "(", attr('start', TimeValue), ")"
class TimeList(List):
grammar = csl([TimePeriod, TimeFixed, TimePeriodWrapped, TimeFixedWrapped], separator=";")
def __str__(self):
for a in self:
print(a.get_as_object())
return ''
class AlertExpression(List):
grammar = '-t', blank, attr('timezone', Timezone), blank, '-n', blank, attr('locale'), blank, "-p", optional(blank), "'", attr('timelist', TimeList), "'"
def get_time_objects(self):
for item in self.timelist:
yield item.get_as_object()
def __str__(self):
return '{} {}'.format(self.timezone, self.locale)
if __name__ == '__main__':
s="""-t gmt+1 -n GB_EN -p '39600-61200,0; (126000-147600,3); -(212400-234000,5); 298800; (320400); 385200-406800,0; 471600-493200,0; 558000-579600,0'"""
p = parse(s, AlertExpression)
print("*"*80)
print(s)
print("*"*80)
print(p)
print("*"*80)
pprint(list(p.get_time_objects()))
print(compose(p))