【问题标题】:Reading and Storing the lines in XML file读取和存储 XML 文件中的行
【发布时间】: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


【解决方案1】:

获取值的一种方法是将它们放在一个列表中,这就是使用正则表达式的方法:

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]

然后您可以在循环中执行此操作,以获取另一个列表中的所有值列表并进一步处理它。

【讨论】:

    【解决方案2】:

    我会使用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.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 2017-09-08
      • 1970-01-01
      • 2013-01-26
      • 1970-01-01
      相关资源
      最近更新 更多