gpt4 book ai didi

python - 如何将 python wordcloud 元素传递给 svgwrite 方法以生成 wordcloud 的 svg?

转载 作者:太空宇宙 更新时间:2023-11-04 05:05:09 28 4
gpt4 key购买 nike

我正在尝试生成由一些硬编码字符串组成的 word_cloud 的 svg(截至目前,稍后将动态生成这些字符串)。下面是生成word_cloud的Python代码:

from os import path
from wordcloud import WordCloud
d = path.dirname(__file__)
# Read the whole text.
#text = open(path.join(d, 'test.txt')).read()
mytext = ['hello, hi, ibm, pune, hola']
# Generate a word cloud image
wordcloud = WordCloud().generate(text)
import svgwrite
# Display the generated image:
# the matplotlib way:
import matplotlib.pyplot as plt
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off")

现在我不想使用 plt.show(),而是想将 wordcloud 变量传递给 svgwrite 方法,如下所示:

svg_document = svgwrite.Drawing(filename = "test-svgwrite.svg",profile = 'full')
svg_document.add(svg_document.text(wordcloud,
insert = (210, 110)))
svg_document.tostring()
svg_document.save()

但是,这个创建的 SVG 不包含任何文字云,只包含文本(如下图所示): check the screenshot here

最佳答案

面对使用 matplotlib 的一些问题(虽然它会保存为“.svg”,但它会结合 wordcloud 使用光栅图形),我想出了另一种方法

wordcloud = WordCloud()
wordcloud.generate_from_frequencies(frequencies=features)
wordcloud_svg = wordcloud.to_svg(embed_font=True)
f = open("filename.svg","w+")
f.write(wordcloud_svg )
f.close()

embed_font bool 值防止单词重叠。您还可以自由修改 wordcloud_svg 以更改颜色、字体等。它具有类似 xml 的结构(打印出来 :))

关于python - 如何将 python wordcloud 元素传递给 svgwrite 方法以生成 wordcloud 的 svg?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44715044/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com