gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 00:22:12 26 4
gpt4 key购买 nike

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

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com