使用python反向模板 [英] reverse template with python

查看:34
本文介绍了使用python反向模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件,里面装满了某种格式的数据,我想用这些数据填充我自己的数据结构

例如,我可以有一个这样的文件:

约翰-史密斯:0123孩子们:山姆金

我想对那个字符串做一些事情,以便将数据提取到例如

firstName = "John"lastName = "史密斯"数字 = "0123"儿童 = ['山姆','金']

我希望有比使用分隔符更简单的方法..

解决方案

这是一个正则表达式解决方案:

<预><代码>>>>进口重新>>>数据 = '约翰 - 史密斯:0123\n儿童:\n 山姆\n 金'>>>match = re.match(r'(\w+) - (\w+) : (\d+).*?children:(.*)', data, re.S)>>>match.groups()(约翰"、史密斯"、0123"、\n 山姆\n 金")

然后您可以将组分配给您的变量:

<预><代码>>>>firstName, lastName, number = match.groups()[:3]>>>children = [c.strip() for c in match.group(4).strip().split('\n')]

结果...

<预><代码>>>>名'约翰'>>>姓'史密斯'>>>数字'0123'>>>孩子们['山姆','金']

I have a file, full of data in a certain format, I want to fill my own data structure with that data

for example, I can have a file like this:

John - Smith : 0123
children: 
  Sam
  Kim

I want to do something with that string, in order to extract the data into for example

firstName = "John"
lastName = "Smith"
number = "0123"
children = ['Sam', 'Kim']

I hope there's an easier way than using separators..

解决方案

Here is a regex solution:

>>> 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')

You can then assign the groups to your variables:

>>> firstName, lastName, number = match.groups()[:3]
>>> children = [c.strip() for c in match.group(4).strip().split('\n')]

and the result...

>>> firstName
'John'
>>> lastName
'Smith'
>>> number
'0123'
>>> children
['Sam', 'Kim']

这篇关于使用python反向模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆