简体   繁体   English

如何从Python修改SVG文件的属性?

[英]How can I modify the attributes of an SVG file from Python?

I have an svg file that was generated by the map data-visualisation software 'Kartograph'. 我有一个由地图数据可视化软件'Kartograph'生成的svg文件。 It contains a large number of paths representing areas on a map. 它包含表示地图上区域的大量路径。 These paths each have some data fields: 这些路径每个都有一些数据字段:

<path d=" ...path info... " data-electorate="Canberra" data-id="Canberra" data-no="23" data-nop="0.92" data-percentile="6" data-state="ACT" data-totalvotes="25" data-yes="2" data-yesp="0.08" id="Canberra"/>

So that I don't have to generate a new svg file every time, I want to modify some attributes, such as the number of 'yes' votes, from within python. 因此我不必每次都生成一个新的svg文件,我想在python中修改一些属性,例如“是”投票的数量。 Specifically, I would like to increment/increase the 'yes' votes value by one (for each execution of the code). 具体来说,我想将'yes'投票值增加/增加一(每次执行代码)。

I have tried lxml and have browsed the documentation for it extensively, but so far this code has not worked: 我已经尝试过lxml并且已经广泛浏览了它的文档,但到目前为止这段代码还没有用:

from lxml import etree

filename = "aus4.svg"
tree = etree.parse(open(filename, 'r'))

for element in tree.iter():
    if element.tag.split("}")[1] == "path":
        if element.get("id") == "Lingiari":
            yes_votes = element.get("data-yes")
            print(yes_votes)
            yes_votes.set(yes_votes, str(int(yes_votes) + 1))
            print(yes_votes)

Is python the best tool to use for this task? python是用于此任务的最佳工具吗? If so how might I change the above code or start afresh. 如果是这样,我怎么能改变上面的代码或重新开始。 Apologies for any confusion. 为任何困惑道歉。 I am new to this 'lxml' module and svg files, so I'm a bit lost. 我是这个'lxml'模块和svg文件的新手,所以我有点迷茫。

You do not set the attribute again, but use its value instead of the elmenet in this line: 您没有再次设置该属性,但在此行中使用其值而不是elmenet:

yes_votes.set(yes_votes, str(int(yes_votes) + 1))

yes_votes contains the content of the attribute and not a reference to the attribute itself. yes_votes包含属性的内容,而不是对属性本身的引用。 Change it to: 将其更改为:

element.set( "data-yes", str(int(yes_votes) + 1))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM