首页 > 解决方案 > 如何将SVG字符串保存到python中的文件

问题描述

顾名思义,我正在使用这个 wordcloud 生成器,并希望将内容保存为.svg. 该库有一个to_svg()函数,它返回一个字符串。它还有一个to_file()不以这种格式保存的。

有什么方法可以使用pyplot's savefig 函数将字符串输出保存to_svg()到文件中?

标签: pythonmatplotlib

解决方案


它不使用pyplot.savefig,但除了wordcloud您链接的库和 Python 本身之外,它不需要任何东西:

from wordcloud import WordCloud

wc = WordCloud()
wc.generate_from_text('This is a word cloud example which has a few words, showing them word for word in a cloud.')

svg_text = wc.to_svg()
with open('my.svg', 'w') as f:
    f.write(svg_text)

输出是您所追求的词 cloud .svg。

这是 InkScape 中 .svg 的屏幕截图


推荐阅读