Pyparsing: 空格作为有效标记

8 投票
2 回答
3696 浏览
提问于 2025-04-16 09:25

我正在使用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

2 个回答

1

考虑使用其他方法来去除空格

>>> s=". a . v a l i d . s t r i n g ."
>>> s=s[::2]
>>> s
'.a.valid.string.'
8

因为这里有很多空白字符,所以你需要告诉你的字符表达式不要去处理开头的空白部分。下面的代码定义了如何做到这一点,看看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____________

撰写回答