我有以下文字:
<clipPath id="p54dfe3d8fa">
<path d="M 112.176 307.8
L 112.176 307.8
L 174.672 270
L 241.632 171.72
L 304.128 58.32
L 380.016 171.72
L 442.512 217.08
L 491.616 141.48
L 491.616 307.8
z
"/>
</clipPath>
<clipPath id="p27c84a8b3c">
<rect height="302.4" width="446.4" x="72.0" y="43.2"/>
</clipPath>
我需要把这部分拿出来:
d="M 112.176 307.8
L 112.176 307.8
L 174.672 270
L 241.632 171.72
L 304.128 58.32
L 380.016 171.72
L 442.512 217.08
L 491.616 141.48
L 491.616 307.8
z
"
我需要用其他内容替换此部分。我能够捕获全部 <clipPath ...><path d="[code i want]"/>但这对我没有帮助,因为我无法覆盖 <clipPath> 中的 ID元素。
注意还有其他<clipPath>我不想碰的元素。我只想改变<path> <clipPath> 中的元素元素。
我认为答案与选择 clipPath 元素之前的所有内容并在 Path 部分结束有关。任何帮助将不胜感激。
我一直在使用 http://pythex.org/寻求帮助,也看到了奇怪的行为(与多行和空格有关)在 python 3.x 代码之间的行为不同。
以下是我尝试过的一些方法:
reg = r'(<clipPath.* id=".*".*>)'
reg = re.compile(r'(<clipPath.* id=".*".*>\s*<path.*d="(.*\n)+")')
reg = re.compile(r'((?<!<clipPath).* id=".*".*>\s*<path.*d="(.*\n)+")')
g = reg.search(text)
g
请您参考如下方法:
正则表达式绝不是解析 xml 的正确方法。
这是一个简单的独立示例,它使用 lxml 实现:
from lxml import etree
text="""<clipPath id="p54dfe3d8fa">
<path d="M 112.176 307.8
L 112.176 307.8
L 174.672 270
L 241.632 171.72
L 304.128 58.32
L 380.016 171.72
L 442.512 217.08
L 491.616 141.48
L 491.616 307.8
z
"/>
</clipPath>
<clipPath id="p27c84a8b3c">
<rect height="302.4" width="446.4" x="72.0" y="43.2"/>
</clipPath>"""
# This creates <metrics>
root = etree.XML("<X>"+text+"</X>")
p = root.find(".//path")
print(p.get("d"))
结果:
M 112.176 307.8 L 112.176 307.8 L 174.672 270 L 241.632 171.72 L 304.128 58.32 L 380.016 171.72 L 442.512 217.08 L 491.616 141.48 L 491.616 307.8 z
- 首先,我创建主节点。由于有几个节点,我把它包装在任意一个主节点
- 然后我到处寻找“路径”
- 一旦找到,我就会得到
d属性
现在我正在更改 d 的文本并将其转储:
p.set("d","[new text]")
print(etree.tostring(root))
现在的输出是这样的:
...
<path d="[new text]"/>\n
...
仍然,快速而肮脏,可能对几个 path 节点不稳健,但可以使用您提供的代码段(我不是 xml 专家,只是笨手笨脚)
顺便说一句,另一种 hacky/非正则表达式的方式:使用多字符 split:
text.split(' d="')[1].split('"/>')[0]
在 d 定界符之后取第二部分,然后在 /> 定界符之后取第一部分。保留多行格式。
