python - 当我写这会从 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 代码,我的印象是它与原始代码相比缺少部分代码图片
解决方案
另一种方法。
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
推荐阅读
- hyperledger-fabric - 查询 Hyperledger Historian 的问题
- pycharm - 在 PyCharm 中可视化点文件
- c++ - 使用 stl 反转链表
- java - 关于 ImageLoader 的 Android Studio 问题
- python - 无论我输入什么,我将数字转换为基数 10 的 python 代码总是输出 1665
- mpi - 使用 MPI_Bcast(...) 广播动态分配的二维数组
- node.js - Vue Node.js/express 应用程序错误无法设置未定义的属性渲染
- java - 在两个相似的模块上同时改变一个变量的值
- angular - 使用角垫表时在控制台上观察到错误
- xml - 如何使用 build.xml 创建名称包含创建日期和时间的文件