Alex提到了pyparsing,这里提供一个使用pyparsing的解决方案来解决你的问题:
from pyparsing import Word, Suppress, Regex, oneOf, SkipTo
import datetime
DASHES = Word('-').suppress()
LPAR,RPAR,AT = map(Suppress,"()@")
date = Regex(r'\d{2}/\d{2}/\d{4}')
time = Regex(r'\d{2}:\d{2}:\d{2}')
status = oneOf("Busy Available Idle Offline Unavailable")
statechange1 = 'changed status from' + status('fromstate') + 'to' + status('tostate')
statechange2 = 'became' + status('tostate')
linefmt = (DASHES + SkipTo('(')('name') + LPAR + SkipTo(RPAR)('email') + RPAR +
(statechange1 | statechange2) +
AT + date('date') + time('time') + DASHES)
def convertFields(tokens):
if 'fromstate' not in tokens:
tokens['fromstate'] = 'NULL'
tokens['name'] = tokens.name.strip()
tokens['email'] = tokens.email.strip()
d,mon,yr = map(int, tokens.date.split('/'))
h,m,s = map(int, tokens.time.split(':'))
tokens['datetime'] = datetime.datetime(yr, mon, d, h, m, s)
linefmt.setParseAction(convertFields)
for line in text.splitlines():
fields = linefmt.parseString(line)
print "%(name)s/%(email)s %(fromstate)-10.10s %(tostate)-10.10s %(datetime)s" % fields
打印:
Mark Grey/mark.grey@gmail.com Busy Available 2010-07-14 16:32:36
Silvia Pablo/spablo@gmail.com NULL Available 2010-07-14 16:32:39
pyparsing允许您为结果字段附加名称(就像Tom Pietzcker的RE-styled答案中的命名组一样),并且可以在解析时执行操作以对解析后的操作进行操作或操作 - 请注意,将单独的日期和时间字段转换为真正的datetime对象,已经转换并准备好在解析后进行处理,无需任何额外的麻烦。
这是一个修改后的循环,它只会转储出每行的解析令牌和命名字段:
for line in text.splitlines():
fields = linefmt.parseString(line)
print fields.dump()
打印:
['Mark Grey ', 'mark.grey@gmail.com', 'changed status from', 'Busy', 'to', 'Available', '14/07/2010', '16:32:36']
- date: 14/07/2010
- datetime: 2010-07-14 16:32:36
- email: mark.grey@gmail.com
- fromstate: Busy
- name: Mark Grey
- time: 16:32:36
- tostate: Available
['Silvia Pablo ', 'spablo@gmail.com', 'became', 'Available', '14/07/2010', '16:32:39']
- date: 14/07/2010
- datetime: 2010-07-14 16:32:39
- email: spablo@gmail.com
- fromstate: NULL
- name: Silvia Pablo
- time: 16:32:39
- tostate: Available
我猜测,当您继续解决这个问题时,您可能会发现输入文本格式的其他变化,以指定用户状态的更改。在这种情况下,您只需要添加另一个定义,例如statechange1
或statechange2
,并将其与其他内容一起插入到linefmt
中。我认为pyparsing对解析器定义的结构化有助于开发人员在事物发生变化后回到解析器,并轻松扩展其解析程序。