我开始学习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"]))
因此,它打印绘图,但我想将其保存到图像文件中。
谢谢!
发布于 2020-08-12 03:44:29
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))), 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')
https://stackoverflow.com/questions/63368379
复制相似问题