我尝试了不同的方法来保存我的情节,但我尝试过的每件事都出现了空白图像,而且我目前还没有失去想法。对可以解决此问题的其他建议有帮助吗?代码示例如下。
word_frequency = nltk.FreqDist(merged_lemmatizedTokens) #obtains frequency distribution for each token
print("\nMost frequent top-10 words: ", word_frequency.most_common(10))
word_frequency.plot(10, title='Top 10 Most Common Words in Corpus')
plt.savefig('img_top10_common.png')
我能够保存 NLTK FreqDist 图,当我首先初始化一个图形对象,然后调用 plot 函数并最终保存图形对象时。
import matplotlib.pyplot as plt
from nltk.probability import FreqDist
fig = plt.figure(figsize = (10,4))
plt.gcf().subplots_adjust(bottom=0.15) # to avoid x-ticks cut-off
fdist = FreqDist(merged_lemmatizedTokens)
fdist.plot(10, cumulative=False)
plt.show()
fig.savefig('freqDist.png', bbox_inches = "tight")
我想你可以尝试以下方法:
plt.ion()
word_frequency.plot(10, title='Top 10 Most Common Words in Corpus')
plt.savefig('img_top10_common.png')
plt.ioff()
plt.show()
这是因为在nltk的
plot
函数中,调用了plt.show()
,一旦图形关闭,plt.savefig()
就没有活动图形可以保存了。
解决方法是打开交互模式,这样 nltk 函数内部的
plt.show()
就不会阻塞。然后使用可用的当前图形调用 savefig 并保存正确的绘图。然后要显示图形,需要再次关闭交互模式并从外部调用plt.show()
——这次是阻塞模式。
理想情况下,
nltk
将重写他们的绘图函数以允许设置阻塞状态,或者不允许 show
绘图并返回创建的图形,或者将 Axes
作为要绘图的输入。请随时通过此请求与他们联系。
我遇到了同样的问题,我解决的方法是在
show=False
函数中使用参数plot()
,正如NLTK库成员here所提到的。
您的代码将保持如下状态:
word_frequency = nltk.FreqDist(merged_lemmatizedTokens)
print("\nMost frequent top-10 words: ", word_frequency.most_common(10))
word_frequency.plot(10, show=False, title='Top 10 Most Common Words in Corpus')
plt.savefig('img_top10_common.png')
重要的是不要在
plt.show()
之前包含plt.savefig()
,因为这样会保存一个空白图。