Skip to main content
 首页 » 编程设计

python 在文件中查找带有路径的图像

2025年04月02日8sharpest

我想在文件中查找 svgs 或 pngs。图片位于属性 v="..."

文件的一部分如下所示:

<symbol alpha="1" type="marker" name="0"> 
<layer pass="0" class="SvgMarker" locked="0"> 
<prop k="angle" v="0"/> 
<prop k="fill" v="#000000"/> 
<prop k="name" v="../Downloads/Inkscape_vectorisation_test.svg"/> 
<prop k="offset" v="0,0"/> 
<prop k="offset_unit" v="MM"/> 
<prop k="outline" v="#000000"/> 
<prop k="outline-width" v="1"/> 
<prop k="outline_width_unit" v="MM"/> 
<prop k="size" v="hello.png"/> 
<prop k="size_unit" v="MM"/> 
</layer> 

我想要一个像这样的列表:

['../Downloads/Inkscape_vectorisation_test.svg','hello.png']

我的 python 代码:

import re 
projectFile = open("project.xml", "r") 
regex = re.compile(r'(?<=v\=").+(\.svg|\.png)(?="/>)') 
 
for line in projectFile: 
    result = regex.findall(line)             
    for filename in result: 
        print filename 

我用 http://pythex.org/ 测试了我的正则表达式它工作正常但在 python 控制台中结果只是 .svg 似乎捕获组 (\.svg|\.png) 被不同地解释。我做错了什么?

请您参考如下方法:

是否要求使用正则表达式?如果不是,一种更简单、更清洁的方法是使用 lxml .

由于您想要的 URI 似乎出现在 k="name" 的 prop 元素中,您可以使用 xpath做类似的事情:

from lxml import etree 
f = etree.parse(projectFile) 
root = f.getroot() 
# This will give you a list with all prop elements that contain the URIs you want in the v attribute 
elements = root.xpath("//prop[@k='name']")