我正在使用pyparser来处理十六进制到文本转换器的输出。它每行打印16个字符,以空格分隔。如果十六进制值是ASCII可打印字符,则打印该字符,否则转换器将输出句点(.)
输出通常如下所示:
. 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 . . . . . . . . . . . .
我描述这一行的pyparsing代码是:
dump_line = 16 * Word(printables, exact=1)
这可以很好地工作,直到十六进制到文本的转换器达到十六进制值0x20,这会导致它输出一个空格。
l i n e . w . a . s p a c e .
在这种情况下,pyparsing会忽略输出的空格,并占用下一行中的字符来构成16个字符的“配额”。
有人可以建议我如何告诉pyparsing期望16个字符,每个字符由空格分隔,其中空格也可以是有效字符吗?
提前谢谢。J
发布于 2011-01-04 22:15:57
因为这里有重要的空格,所以你需要告诉你的字符表达式不要使用前导空格。在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____________
发布于 2011-01-04 22:19:30
考虑使用另一种方法删除空格
>>> s=". a . v a l i d . s t r i n g ."
>>> s=s[::2]
>>> s
'.a.valid.string.'
https://stackoverflow.com/questions/4598764
复制相似问题