【问题标题】:Change the color of x SVG files更改 x SVG 文件的颜色
【发布时间】:2020-10-04 13:00:48
【问题描述】:

我想更改至少 1.000 个 SVG 文件的颜色。我遇到的主要问题是当前的 SVG 不包含“fill”属性,所以我必须在 SVG 标记的末尾添加 fill="X"。

这是一个 SVG 文件的示例:

<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 19.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0)  -->
<svg version="1.1" id="Layer_1" " x="0px" y="0px"
     viewBox="-236 286 30 30" style="enable-background:new -236 286 30 30;" xml:space="preserve">

感谢您的帮助。

【问题讨论】:

  • 您能提供更多信息吗?您是否已经尝试过一些正则表达式?结果应该如何?
  • 感谢您的快速回答。结果应如下所示: fill="red" >
  • 你知道regex101.com这个网站吗?我在使用正则表达式时经常使用该页面。
  • 你打算如何使用 svg 元素?如果您使用的是内联 svg,您可以在 css 中设置填充,例如 svg{fill:red}

标签: regex string loops svg colors


【解决方案1】:

有很多方法可以做到这一点。最安全的方法是读取 XML 结构,然后对其进行操作。但是对于那个特定的例子,你也可以使用下面的正则表达式,例如sed 或 python:

使用 sed:

sed -E 's/xml:space=\"preserve\">/xml:space="preserve" fill="red" >/gm;t;d' 

使用 Python:

import re

regex = r"xml:space=\"preserve\">"

test_str = ("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
    "<!-- Generator: Adobe Illustrator 19.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0)  -->\n"
    "<svg version=\"1.1\" id=\"Layer_1\" \" x=\"0px\" y=\"0px\"\n"
    "     viewBox=\"-236 286 30 30\" style=\"enable-background:new -236 286 30 30;\" xml:space=\"preserve\">")

subst = "xml:space=\"preserve\" fill=\"red\" >"

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)

if result:
    print (result)

你也可以看看regex101.com/r/cIfbEd

【讨论】:

  • 我以另一种方式做到了。我使用 BBEdit 找到提到的字符串并将其替换为我希望的颜色属性。感谢您朝正确的方向踢球。 :)
猜你喜欢
  • 2020-03-31
  • 1970-01-01
  • 2021-10-31
  • 2013-10-27
  • 2015-11-08
  • 2018-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多