python - 标记嵌套表达式但忽略带空格的引用字符串

标签 python pyparsing

我希望漂亮地打印以下字符串

r"file='//usr/env/0/test/0', name='test', msg=Test.Msg(type=String, bytes_=Bytes(value=b\" 0\x80\x00\x00y\x17\`\"))"

    file='//usr/env/0/test/0',
    name='test',
    msg=Test.Msg(
        type=String,
        bytes=Bytes(
            value=b\" 0\x80\x00\x00y\x17\`\""
        )
    )

首先,我尝试使用 pyparsing 来标记输入

from pyparsing import *
content = r"(file='//usr/env/0/test/0', name='test', msg=Test.Msg(type=String, bytes_=Bytes(value=b\" 0\x80\x00\x00y\x17\`\")))"
expr     = nestedExpr( '(', ')', ignoreExpr=None)
result = expr.parseString(content)
result.pprint()

这给了我一个嵌套列表,但字节数组在空格上被分割

[["file='//usr/env/0/test/0',",
  "name='test',",
  'msg=Test.Msg',
  ['type=String,',
   'bytes_=Bytes',
   ['value=b\\"', '0\\x80\\x00\\x00y\\x17\\`\\"']]]]

有人知道如何用逗号分隔来返回以下内容吗?

[["file='//usr/env/0/test/0',",
  "name='test',",
  'msg=Test.Msg',
  ['type=String,',
   'bytes_=Bytes',
   ['value=b\\" 0\\x80\\x00\\x00y\\x17\\`\\"']]]]

最佳答案

为了获得所需的结果,我们需要为嵌套表达式的内容定义一个内容表达式。默认内容是任何带引号的字符串或空格分隔的单词。但我认为你的内容更像是一个逗号分隔的列表。

Pyparsing 在 pyparsing_common 中定义了一个 comma_separated_list 表达式,但它在这里不起作用,因为它不明白嵌套表达式的 () 不应该是逗号中项目的一部分- 单独的列表。所以我们必须编写一个稍加修改的版本:

from pyparsing import *
content = r"""(file='//usr/env/0/test/0', name='test', msg=Test.Msg(type=String, bytes_=Bytes(value=b" 0\x80\x00\x00y\x17\`")))"""

# slightly modified comma_separated_list from pyparsing_common
commasepitem = (
        Combine(
            OneOrMore(
                ~Literal(",")
                + Word(printables, excludeChars="(),")
                + Optional(White(" ") + ~FollowedBy(oneOf(", ( )")))
            )
        )
    )
comma_separated_list = delimitedList(quotedString() | commasepitem)

expr     = nestedExpr( '(', ')', content=comma_separated_list)

result = expr.parseString(content)
result.pprint(width=60)

print(result.asList() == 
        [["file='//usr/env/0/test/0'",
          "name='test'",
          'msg=Test.Msg',
          ['type=String',
           'bytes_=Bytes',
           ['value=b" 0\\x80\\x00\\x00y\\x17\\`"']]]])

打印:

[["file='//usr/env/0/test/0'",
  "name='test'",
  'msg=Test.Msg',
  ['type=String',
   'bytes_=Bytes',
   ['value=b" 0\\x80\\x00\\x00y\\x17\\`"']]]]
True

关于python - 标记嵌套表达式但忽略带空格的引用字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58885185/

相关文章:

python - Numpy 中坐标距离的向量化

Python。学习 turtle graphics

python - pyqt5 textedit 删除经过指定行的行

python - 匹配特定字符串,忽略其他字符串

python - python 中无法识别的 com_error

python - 从 ffmpeg 获取实时输出以在进度条中使用(PyQt4,stdout)

python - 为什么带空格的搜索词在 pyparsing 中不能正确解析?

python - pyparsing:字典列表的语法(erlang)

python - 如何在 pyparsing 中迭代 ParseResults

python - 从python中的字符串解析嵌套逻辑