【发布时间】:2016-05-05 16:15:46
【问题描述】:
我有一个这样的 XML 文件:
<svg version="1.1" xmlns="http://www.w3.org/2000/svg">
<path d="M 50 50 L 50 90 L 90 90 z" fill="red"/>
<path d="M 160 170 L 160 130 L 120 130 z" fill="green"/>
<path d="M 200 30 L 180 30 L 180 50 L 220 50 z" fill="blue"/>
<path d="M 40 100 L 40 140 L 60 140 L 60 120 z" fill="yellow"/>
<path d="M 210 70 L 230 90 L 270 90 L 270 50 L 230 50 z" fill="purple"/>
<path d="M 180 130 L 180 170 L 220 210 L 240 190 z" fill="olive"/>
<path d="M 100 200 L 120 180 L 80 140 L 80 180 z" fill="magenta"/>
</svg>
这些是我必须使用的形状的坐标。我要做的是获取这些形状的所有坐标并分别存储它们。为了进行数学计算。就像得到 x1=50 x2=50 x3=90 y1=50 y2=90 y3=90 为第一个(红色)
如何编译这些行并存储坐标?
编辑:我解决了它并想与人们分享。 此代码获取形状的 X 和 Y 坐标的值和颜色,并将它们存储在列表中。感谢以下建议:
import xml.etree.ElementTree as ET
import re
r = re.compile('[0-9]{1,}')
root = ET.parse('pieces_A.xml').getroot()
line=[]
y=[]
X=[]
Y=[]
newlist=[]
c=[]
i=0
#gets the numbers and colours.
for child in root:
line.append((child.attrib['d']))
c.append(child.attrib)
y.append((r.findall(line[i])))
i +=1
#appends the colours and x,y cordinates to a new list
for i in range(len(y)):
for j in range(len(y[i])):
if j%2==0:
X.append(y[i][j])
if j%2==1:
Y.append(y[i][j])
newlist.append([ X,Y,c[i]['fill'] ] )
X=[]
Y=[]
print(newlist)
所以现在对每个项目所做的是,前 3 个点是 x 坐标,第二个点是 y 坐标,最后一个元素是形状的颜色:
[[['50', '50', '90'], ['50', '90', '90'], 'red'],
【问题讨论】:
-
我认为 parsing the xml 然后只吐出字段字符串会更容易,然后在整个文件上使用 re 。但我可能是错的。
-
感谢您的建议。至少我缩小了一点。
标签: python python-3.x