所以我想这样做(但使用 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 匹配
我知道我可以使用 Words,但我想做
all printables but not the Literal
我该如何实现这个目标?谢谢。
最佳答案
你不应该需要负面的前瞻,即。这个:
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']]
关于python - 基于 pyparsing 的分割,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54795385/