Pyparsing 擅长从简单的表达式组合复杂的表达式,并且包含许多用于可选、无序和逗号分隔值的内置函数。请参阅下面代码中的 cmets:
import pyparsing as pp
real = pp.pyparsing_common.real
integer = pp.pyparsing_common.integer
name = pp.Word(pp.alphas, min=2, max=4)
# a valid person entry starts with a name followed by an optional !integer for age
# and an optional |real for weight; the '&' operator allows these to occur in either
# order, but at most only one of each will be allowed
expr = pp.Group(name("name")
+ (pp.Optional(pp.Suppress('!') + integer("age"), default='')
& pp.Optional(pp.Suppress('|') + real("weight"), default='')))
# other entries that we don't care about
other = pp.Word(pp.alphas, min=5)
# an expression for the complete input line - delimitedList defaults to using
# commas as delimiters; and we don't really care about the other entries, just
# suppress them from the results; whitespace is also skipped implicitly, but that
# is not an issue in your given sample text
input_expr = pp.delimitedList(expr | pp.Suppress(other))
# try it against your test data
text = "Louis,Edward,John|85.56!26,Billy,Don!18|78.0,Dean"
input_expr.runTests(text)
打印:
Louis,Edward,John|85.56!26,Billy,Don!18|78.0,Dean
[['John', 85.56, 26], ['Don', 18, 78.0], ['Dean', '', '']]
[0]:
['John', 85.56, 26]
- age: 26
- name: 'John'
- weight: 85.56
[1]:
['Don', 18, 78.0]
- age: 18
- name: 'Don'
- weight: 78.0
[2]:
['Dean', '', '']
- name: 'Dean'
在这种情况下,使用预定义的实数和整数表达式不仅可以解析值,还可以转换为 int 和 float。命名参数可以像对象属性一样访问:
for person in input_expr.parseString(text):
print("({!r}, {}, {})".format(person.name, person.age, person.weight))
给予:
('John', 26, 85.56)
('Don', 18, 78.0)
('Dean', , )