发布
社区首页 >问答首页 >如何保存到img "dispersion_plot“NLTK?

如何保存到img "dispersion_plot“NLTK?
EN

Stack Overflow用户
提问于 2020-08-12 09:14:41
回答 1查看 150关注 0票数 0

我开始学习NLTK了。有没有一种方法可以保存到镜像的dispersion_plot?

这是我的代码:

代码语言:javascript
代码运行次数:0
复制
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"]))

因此,它打印绘图,但我想将其保存到图像文件中。

谢谢!

EN

回答 1

Stack Overflow用户

发布于 2020-08-12 11:44:29

代码语言:javascript
代码运行次数:0
复制
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')

编辑:保存散点图而不打印

代码语言:javascript
代码运行次数:0
复制
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')
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63368379

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档