如何解决如何保存到img“ dispersion_plot” NLTK?
我开始学习NLTK。有没有一种方法可以保存对dispersion_plot的图像?
这是我的代码:
import nltk
from nltk import word_tokenize
raw="""This is the text where includes the word lawyers"""
text1 = nltk.Text(word_tokenize(raw))
print(text1.dispersion_plot(["lawyers"]))
因此,它会打印出情节,但我想将其保存到图像文件中。
谢谢!
解决方法
import nltk
from nltk import word_tokenize
import matplotlib.pyplot as plt
raw="This is the text where includes the word lawyers"
text1 = nltk.Text(word_tokenize(raw))
fig = plt.figure()
dplot = text1.dispersion_plot(["lawyers"])
# save the figure
fig.savefig('dispersion_plot.png')
编辑:保存色散图而无需绘制
import nltk
from nltk import word_tokenize
from matplotlib import pylab
def dispersion_plot(text,words,ignore_case=False,title="Lexical Dispersion Plot",filename='dispersion_plot.png'):
text = list(text)
words.reverse()
if ignore_case:
words_to_comp = list(map(str.lower,words))
text_to_comp = list(map(str.lower,text))
else:
words_to_comp = words
text_to_comp = text
points = [
(x,y)
for x in range(len(text_to_comp))
for y in range(len(words_to_comp))
if text_to_comp[x] == words_to_comp[y]
]
if points:
x,y = list(zip(*points))
else:
x = y = ()
pylab.plot(x,y,"b|",scalex=0.1)
pylab.yticks(list(range(len(words))),color="b")
pylab.ylim(-1,len(words))
pylab.title(title)
pylab.xlabel("Word Offset")
# pylab.show()
pylab.savefig(filename)
raw = "This is the text where includes the word lawyers"
text1 = nltk.Text(word_tokenize(raw))
dispersion_plot(text=text1,words=["lawyers"],filename='dispersion_plot.png')
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。