将Spacy渲染文件另存为SVG文件

时间:2019-05-17 07:47:46

标签: python spacy

我有以下代码:

import spacy
from spacy import displacy
from pathlib import Path

nlp = spacy.load('en_core_web_sm', parse=True, tag=True, entity=True)

sentence_nlp = nlp("John go home to your family")
svg = displacy.render(sentence_nlp, style="dep", jupyter=True)

output_path = Path("/images/dependency_plot.svg")
output_path.open("w", encoding="utf-8").write(svg)

我正在尝试将渲染的文件写入images文件夹中的svg文件。 但是,我得到了错误:

  

回溯(最近通话最近一次):

     

文件“”,第8行,在       output_path.open(“ w”,encoding =“ utf-8”)。write(svg)

     

文件   “ C:\ Users **** \ AppData \ Local \ Continuum \ miniconda3 \ lib \ pathlib.py”,   1183行,处于打开状态       opener = self._opener)

     

文件   “ C:\ Users **** \ AppData \ Local \ Continuum \ miniconda3 \ lib \ pathlib.py”,   _opener中的第1037行       返回self._accessor.open(self,标志,模式)

     

文件   “ C:\ Users **** \ AppData \ Local \ Continuum \ miniconda3 \ lib \ pathlib.py”,   387号线,缠绕       返回strfunc(str(pathobj),* args)   FileNotFoundError:[错误2]没有这样的文件或目录:   '\ images \ dependency_plot.svg'

该目录确实存在,所以我不太确定自己在做什么错。我还查看了spacy用法页面https://spacy.io/usage/visualizers#jupyter,无法弄清楚我在做什么错。我正在使用spyder(如果需要此信息)。 请协助。

2 个答案:

答案 0 :(得分:1)

我认为您那里有2个错误。 首先,您应该修复路径-添加“。”

来自:

output_path = Path("/images/dependency_plot.svg")

收件人:

output_path = Path("./images/dependency_plot.svg")

第二个错误在这一行

svg = displacy.render(sentence_nlp, style="dep", jupyter=True)

我认为您需要删除jupyter=True才能将其写入svg文件。否则,您将得到类似TypeError: write() argument must be str, not None

的错误

这对我有用:

import spacy
from spacy import displacy
from pathlib import Path

nlp = spacy.load('en_core_web_sm', parse=True, tag=True, entity=True)

sentence_nlp = nlp("John go home to your family")
svg = displacy.render(sentence_nlp, style="dep")

output_path = Path("./images/dependency_plot.svg") # you can keep there only "dependency_plot.svg" if you want to save it in the same folder where you run the script 
output_path.open("w", encoding="utf-8").write(svg)

答案 1 :(得分:0)

我按照@Petr Matuska 的回答,遇到了每个人都在评论的错误。在调试时,我发现了 SpaCy documentation 中也提到的两个问题。

  • 要保存时在渲染方法中包含 jupyter=False 树作为 SVG。这样你就不会在 Jupyter 上看到输出,但你 可以打开保存的文件查看结果。
  • 使用整个文档 render 而不是单个句子。请参阅他们的说明 官网
<块引用>

重要说明 由于每个可视化都是作为单独的 SVG,导出 .svg 文件仅适用于渲染单个文件 一次医生。 (这是有道理的——毕竟,每个可视化 应该是一个独立的图形。)所以而不是在 一,遍历它们并分别导出。

  • 对于单个句子,将其用作 sentences = ["This is an example."]

这是直接来自 SpaCy documentation 的代码片段,非常适合我。

import spacy
from spacy import displacy
from pathlib import Path

nlp = spacy.load("en_core_web_sm")
sentences = ["This is an example.", "This is another one."]
for sent in sentences:
    doc = nlp(sent)
    svg = displacy.render(doc, style="dep", jupyter=False)
    file_name = '-'.join([w.text for w in doc if not w.is_punct]) + ".svg"
    output_path = Path("/images/" + file_name)
    output_path.open("w", encoding="utf-8").write(svg)