易于使用的模式匹配和信息提取
stringparser的Python项目详细描述
动机
stringparser模块提供了匹配模式和提取 字符串中的信息。因为模式是用熟悉的格式给出的 字符串规范PEP 3101,编写它们比编写要容易得多 正则表达式(尽管功能不太强大)。
示例
您可以构建一个可重用的解析器对象:
>>> parser = Parser('The answer is {:d}') >>> parser('The answer is 42') 42 >>> parser('The answer is 54') 54
或直接:
>>> Parser('The answer is {:d}')('The answer is 42') 42
您可以检索许多字段:
>>> Parser('The {:s} is {:d}')('The answer is 42') ('answer', 42)
您可以使用编号字段对返回的元组进行排序:
>>> Parser('The {1:s} is {0:d}')('The answer is 42') (42, 'answer')
或命名字段返回ordereddict:
>>> Parser('The {a:s} is {b:d}')('The answer is 42') OrderedDict([('a', 'answer'), ('b', 42)])
您可以忽略一些使用“作为名称”的字段:
>>> Parser('The {_:s} is {:d}')('The answer is 42') 42
限制
- 从格式字符串:
[[填充]对齐][符号][][0][最小宽度][.精度][类型]
目前只实现了类型、符号和。
这可能会给匹配某些符号带来麻烦,例如:
- 十进制:'-4'写为'-4'
- 等
- 行从头到尾匹配。{:d}不会返回所有 字符串中的数字。使用正则表达式。