【问题标题】:Editing a svg (lxml) file whith beautifulsoup and regular expression使用 beautifulsoup 和正则表达式编辑 svg (xml) 文件
【发布时间】:2020-05-24 12:22:05
【问题描述】:

我正在尝试制作一个修改 .svg 文件(XML 格式)的脚本。我正在尝试更改一个或多个对象(例如数组)的背景颜色。

目前我认为我已经通过了我的代码的第一部分,但我看不到如何注册我的颜色更改。

这是我的代码:

From bs4 import BeautifulSoup
import re

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

paths = soup.find_all('path')

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

    print(path.attrs['style'])
svg = open ('draw.svg' ,"w")
svg.write(paths)
svg.close()

我要修改的内容位于包含 4 个不同属性( id 、 style ...)的路径标记中 目前我很难识别我的 id 然后是样式,然后我放了一个正则表达式,我尝试更改值,但它不会改变原始文件的任何内容。我想我错过了一些东西,你能通过建议我怎么做来帮助我吗?

我看不到如何同时读取/写入文件。

【问题讨论】:

  • 你能把实际draw.svg的xml贴出来吗?

标签: python regex beautifulsoup lxml


【解决方案1】:

如果我理解正确,您想使用id='5' 编辑路径。然后你想将包含fillstyle 属性更改为FFFFFF。然后将其写入文件。你可以这样做:

from bs4 import BeautifulSoup
import re

# Opening files using the with statement is generally recommended
# because it ensures that open file descriptors are
# closed automatically after program execution leaves the context
# of the with statement
with open('draw.svg') as file:
    svg = file.read()

soup = BeautifulSoup(svg, 'lxml')

svg_tag = soup.find('svg')
path = svg_tag.find('path', {'id': '5'})
# There can be spaces between the fill and : and hex
# then either 1 or 2 groups of 3 alphanumeric characters.
# It can be multiline
path['style'] = re.sub(
    r'fill\s*:\s*#([a-fA-F0-9]{3}){1,2}',
    r'fill:#FFFFFF',
    path['style'],
    re.M
)

# print(soup)

# Open the file again using the with statement and write the svg tag contents.
with open('draw.svg', 'w') as file:
    file.write(str(svg_tag))

输入(draw.svg):

<svg width="450" height="450">
   <path id="5" d="M100,100 L150,100 L150,150  Z"
      style="stroke: #0000cc;
             stroke-width: 2px;
             fill  : #ccccff;"/>
</svg> 

输出(draw.svg):

<svg height="450" width="450">
<path d="M100,100 L150,100 L150,150  Z" id="5" style="stroke: #0000cc;
             stroke-width: 2px;
             fill:#FFFFFF;"></path>
</svg>

【讨论】:

    猜你喜欢
    • 2018-08-05
    • 1970-01-01
    • 1970-01-01
    • 2019-09-18
    • 2020-09-29
    • 1970-01-01
    • 2021-12-24
    • 2012-05-12
    • 2012-09-01
    相关资源
    最近更新 更多