将空间渲染文件另存为svg-fi

2024-06-08 22:09:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码:

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(如果需要这个信息)。 请协助。在


Tags: pathinsvgimporttrueoutputnlpspacy
1条回答
网友
1楼 · 发布于 2024-06-08 22:09:41

我想你有两个错误。 首先你应该修正你的路径-添加“.”

发件人:

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

收件人:

^{pr2}$

第二个错误在这一行

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)

相关问题 更多 >