我正在尝试生成由一些硬编码字符串组成的 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 的结构(打印出来 :))
