我需要在双括号上拆分以空格分隔的 TCL 列表...例如...
OUTPUT = """{{172.25.50.10:01:01-Ethernet 172.25.50.10:01:02-Ethernet {Traffic Item 1}}} {{172.25.50.10:01:02-Ethernet 172.25.50.10:01:01-Ethernet {Traffic Item 1}}}"""
这应该解析为...
OUTPUT = ["""{{172.25.50.10:01:01-Ethernet 172.25.50.10:01:02-Ethernet {Traffic Item 1}}}""",
"""{{172.25.50.10:01:02-Ethernet 172.25.50.10:01:01-Ethernet {Traffic Item 1}}}"""]
我努力了...
import re
splitter = re.compile('}}\s+{{')
splitter.split(OUTPUT)
然而,这会修剪中心的大括号......
['{{172.25.50.10:01:01-Ethernet 172.25.50.10:01:02-Ethernet {Traffic Item 1}',
'172.25.50.10:01:02-Ethernet 172.25.50.10:01:01-Ethernet {Traffic Item 1}}}']
我不知道如何只在之间的空格上进行分割}} {{
。我知道我可以作弊并手动插入缺失的大括号,但我宁愿找到一种简单的方法来有效地解析它。
有没有办法解析OUTPUT
with re.split
(或其他一些Python解析框架)对于任意数量的空格分隔的行包含{{content here}}
?
自从 comp.lang.python 讨论以来,Pyparsing 已经得到了改进,我认为即使是 Cameron Laird 也不会抱怨使用 pyparsing 的解决方案nestedExpr
method:
OUTPUT = """{{172.25.50.10:01:01-Ethernet 172.25.50.10:01:02-Ethernet {Traffic Item 1}}} {{172.25.50.10:01:02-Ethernet 172.25.50.10:01:01-Ethernet {Traffic "Item 1"}}}"""
from pyparsing import nestedExpr, originalTextFor
nestedBraces1 = nestedExpr('{', '}')
for nb in nestedBraces1.searchString(OUTPUT):
print nb
nestedBraces2 = originalTextFor(nestedExpr('{', '}'))
for nb in nestedBraces2.searchString(OUTPUT):
print nb
Prints:
[[['172.25.50.10:01:01-Ethernet', '172.25.50.10:01:02-Ethernet', ['Traffic', 'Item', '1']]]]
[[['172.25.50.10:01:02-Ethernet', '172.25.50.10:01:01-Ethernet', ['Traffic', '"Item 1"']]]]
['{{172.25.50.10:01:01-Ethernet 172.25.50.10:01:02-Ethernet {Traffic Item 1}}}']
['{{172.25.50.10:01:02-Ethernet 172.25.50.10:01:01-Ethernet {Traffic "Item 1"}}}']
如果您必须重新分割数据才能从嵌套大括号中获取各个项目,则原始嵌套列表输出为nestedExpr
可能会有更好的帮助(请注意,即使列表中包含带引号的字符串,带引号的项目也会保留为自己的项目)。但如果您真的非常想要包含嵌套大括号的字符串,请使用以下形式originalTextFor
显示在nestedBraces2
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)