所以我想这样做(但使用pyparsing)
Package:numpy11 Package:scipy
will be split into
[["Package:", "numpy11"], ["Package:", "scipy"]]
到目前为止,我的代码是
package_header = Literal("Package:")
single_package = Word(printables + " ") + ~Literal("Package:")
full_parser = OneOrMore( pp.Group( package_header + single_package ) )
当前输出是这个
([(['Package:', 'numpy11 Package:scipy'], {})], {})
我希望有这样的东西
([(['Package:', 'numpy11'], {})], [(['Package:', 'scipy'], {})], {})
基本上其余的文本与pp.printables匹配
我知道我可以使用Word,但是我想这样做
all printables but not the Literal
我该如何完成?谢谢。
答案 0 :(得分:4)
您不需要负前瞻,即。这个:
from pyparsing import *
package_header = Literal("Package:")
single_package = Word(printables)
full_parser = OneOrMore( Group( package_header + single_package ) )
print full_parser.parseString("Package:numpy11 Package:scipy")
打印:
[['Package:', 'numpy11'], ['Package:', 'scipy']]
更新:要解析由|
分隔的软件包,您可以使用delimitedList()
函数(现在软件包名称中也可以有空格):
from pyparsing import *
package_header = Literal("Package:")
package_name = Regex(r'[^|]+') # | is a printable, so create a regex that excludes it.
package = Group(package_header + package_name)
full_parser = delimitedList(package, delim="|" )
print full_parser.parseString("Package:numpy11 foo|Package:scipy")
打印:
[['Package:', 'numpy11 foo'], ['Package:', 'scipy']]