由于这有很大的空白,您需要告诉您的角色表达式不要单独留下前导空白。在下面的 dumpchar 定义中查看这是如何完成的:
hexdump = """\
. a . v a l i d . s t r i n g .
. a n o t h e r . s t r i n g .
. e t c . . . . . . . . . . . .
l i n e . w . a . s p a c e .
. e t c . . . . . . . . . . . .
"""
from pyparsing import oneOf, printables, delimitedList, White, LineEnd
# expression for a single char or space
dumpchar = oneOf(list(printables)+[' ']).leaveWhitespace()
# convert '.'s to something else, if you like; in this example, '_'
dumpchar.setParseAction(lambda t:'_' if t[0]=='.' else None)
# expression for a whole line of dump chars - intervening spaces will
# be discarded by delimitedList
dumpline = delimitedList(dumpchar, delim=White(' ',exact=1)) + LineEnd().suppress()
# if you want the intervening spaces, use this form instead
#dumpline = delimitedList(dumpchar, delim=White(' ',exact=1), combine=True) + LineEnd().suppress()
# read dumped lines from hexdump
for t in dumpline.searchString(hexdump):
print ''.join(t)
印刷:
_a_valid_string_
_another_string_
_etc____________
line_w_a_ space_
_etc____________