【问题标题】:reverse template with python使用python反向模板
【发布时间】:2011-11-03 20:37:06
【问题描述】:
我有一个文件,里面有某种格式的数据,我想用那个数据填充我自己的数据结构
例如,我可以有这样的文件:
John - Smith : 0123
children:
Sam
Kim
我想用那个字符串做一些事情,以便将数据提取到例如
firstName = "John"
lastName = "Smith"
number = "0123"
children = ['Sam', 'Kim']
我希望有比使用分隔符更简单的方法..
【问题讨论】:
标签:
python
regex
string
templates
【解决方案1】:
这是一个正则表达式解决方案:
>>> import re
>>> data = 'John - Smith : 0123\nchildren: \n Sam\n Kim'
>>> match = re.match(r'(\w+) - (\w+) : (\d+).*?children:(.*)', data, re.S)
>>> match.groups()
('John', 'Smith', '0123', ' \n Sam\n Kim')
然后您可以将组分配给您的变量:
>>> firstName, lastName, number = match.groups()[:3]
>>> children = [c.strip() for c in match.group(4).strip().split('\n')]
结果……
>>> firstName
'John'
>>> lastName
'Smith'
>>> number
'0123'
>>> children
['Sam', 'Kim']