首页 > 解决方案 > 当我写这会从 svg 文件中删除所有数据

问题描述

我在使用 Python 2.7 中修改 SVG 文件的代码时遇到问题。简单地说,它根据输入的 id 在不同的表中为一个框着色。但是当我运行它时,它使我成为一个空文件。

from bs4 import BeautifulSoup
import re

    svg = (open('Draw.svg').read())
    soup = BeautifulSoup(svg, 'lxml')

    tags = soup.find_all('path')

    for path in tags:
        if path.attrs['id']==('FFF'):
            print(path.attrs['style'])
            Str = re.sub( r'fill:#[0-9a-fA-F]{6}',
                     r'fill:#ffffff',
                     path.attrs['style'])
            path.attrs['style'] = Str
            print(Str)

            print(path.attrs['style'])

    svg = open('Draw.svg', 'w')
    #svg.write(tags)
    svg.close()

我错过了什么?任何帮助,将不胜感激。

我也在考虑改进代码以有多个输入来一次为更多的框着色。

我更改了一些代码,它总是返回一个空文件,但是当我尝试打开它时出现错误:

第 1 行第 1 列上的错误域 1 代码 4

with open('Draw.svg', 'w') as file:
    file.write(str(tags))

当我收到此错误时,我的代码执行得很好,我通过打开 svg 的 xml 代码文件来检查它,但它搞砸了 xml 代码,我的印象是它与原始代码相比缺少部分代码图片

标签: pythonregexbeautifulsoup

解决方案


另一种方法。

from simplified_scrapy import SimplifiedDoc, req, utils
# svg = utils.getFileContent('Draw.svg')
svg = '''
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
  <path id="FFF" style="fill:#aabbcc" />
</svg>
''' # Your svg content
doc = SimplifiedDoc(svg)

tags = doc.selects('path#FFF')

for path in tags:
    print(path['style'])
    Str = doc.replaceReg(path['style'], 'fill:#[0-9a-fA-F]{6}', 'fill:#ffffff')
    path.setAttr('style', Str)
    print(Str)
    print(path['style'])

utils.saveFile('Draw.svg', doc.html)

结果:

<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
  <path id="FFF" style="fill:#ffffff" />
</svg>

这里有更多例子:https ://github.com/yiyedata/simplified-scrapy-demo/tree/master/doc_examples


推荐阅读