关于python:将spacy渲染文件另存为svg文件

Save spacy render file as svg file

我有以下代码:

1
2
3
4
5
6
7
8
9
10
11
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文件。
但是,我得到了错误:

Traceback (most recent call last):

File"", line 8, in
output_path.open("w", encoding="utf-8").write(svg)

File
"C:\\Users****\\AppData\\Local\\Continuum\\miniconda3\\lib\\pathlib.py",
line 1183, in open
opener=self._opener)

File
"C:\\Users****\\AppData\\Local\\Continuum\\miniconda3\\lib\\pathlib.py",
line 1037, in _opener
return self._accessor.open(self, flags, mode)

File
"C:\\Users****\\AppData\\Local\\Continuum\\miniconda3\\lib\\pathlib.py",
line 387, in wrapped
return strfunc(str(pathobj), *args)
FileNotFoundError: [Errno 2] No such file or directory:
'\\images\\dependency_plot.svg'

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


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

从:

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

至:

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

第二个错误在这一行

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

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

这对我有用:

1
2
3
4
5
6
7
8
9
10
11
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)