簡體   English   中英

讀取和存儲XML文件中的行

[英]Reading and Storing the lines in XML file

我有一個像這樣的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為第一個(紅色)

如何編譯這些行並存儲cordinates?

編輯:我解決了它,想與人分享。 此代碼獲取形狀的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)

所以現在做的是每個項目的前三個點是x坐標,第二個點是y坐標,最后一個元素是形狀的顏色:

[[['50', '50', '90'], ['50', '90', '90'], 'red'], 

我會使用ElementTree模塊來解析文件。 以這種方式獲取d=屬性要簡單得多,然后您可以使用正則表達式解析它們。

import xml.etree.ElementTree as ET

root = ET.parse('/path/to/file').getroot()

for child in root:
    print(child.attrib['d']) # store this as variable and then parse to your variables.

獲取值的一種方法是將它們放入列表中,這是使用正則表達式執行此操作的方法:

import re
#Search for numbers
r = re.compile('[0-9]{1,}')
s = 'M 100 200 L 120 180 L 80 140 L 80 180 z'
r.findall(s)
#Returns a list of strings having numbers
['100', '200', '120', '180', '80', '140', '80', '180']
#Map the results to int to get integers
map(int, r.findall(s))
#Returns a list of integers
[100, 200, 120, 180, 80, 140, 80, 180]

然后,您可以在循環內執行此操作,以獲取另一個列表中的所有值列表並進一步處理它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM