【问题标题】:How can I modify the attributes of an SVG file from Python?如何从 Python 修改 SVG 文件的属性?
【发布时间】:2015-03-23 08:40:31
【问题描述】:

我有一个由地图数据可视化软件“Kartograph”生成的 svg 文件。它包含大量代表地图上区域的路径。这些路径每个都有一些数据字段:

<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"/>

为了不用每次都生成一个新的svg文件,我想在python中修改一些属性,比如“是”票的数量。具体来说,我想将“是”投票值增加/增加一(对于代码的每次执行)。

我已经尝试过 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)

python 是完成这项任务的最佳工具吗?如果是这样,我该如何更改上述代码或重新开始。对任何混淆表示歉意。我是这个'lxml'模块和svg文件的新手,所以我有点迷茫。

【问题讨论】:

    标签: python svg lxml


    【解决方案1】:

    您没有再次设置该属性,而是在此行中使用其值而不是 elmenet:

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

    yes_votes 包含属性的内容,而不是对属性本身的引用。将其更改为:

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

    【讨论】:

    • 谢谢你,成功了。抱歉这个愚蠢的问题 - 我已经挣扎了一段时间,显然忽略了这个问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-27
    • 2017-09-17
    • 2016-07-01
    • 2019-11-04
    • 2014-04-14
    • 1970-01-01
    相关资源
    最近更新 更多