我有以下代码:
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)
我正在尝试将渲染的文件写入图像文件夹中的 svg 文件。
但是,我收到错误:
回溯(最近一次调用最后一次):
文件“”,第 8 行,位于
输出路径.open(“w”,编码=“utf-8”).write(svg)
文件
“C:\ Users **** \ AppData \ Local \ Continuum \ miniconda3 \ lib \ pathlib.py”,
1183线,开放中
开瓶器=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: [Errno 2] 没有这样的文件或目录:
'\images\dependency_plot.svg'
该目录确实存在,所以我不太确定我做错了什么。我还查看了 spacy 使用页面https://spacy.io/usage/visualizers#jupyter https://spacy.io/usage/visualizers#jupyter并且无法弄清楚我做错了什么。我正在使用spyder(如果需要此信息)。
请协助。
我认为你有两个错误。
首先你应该修复你的路径 - 添加“。”
from:
output_path = Path("/images/dependency_plot.svg")
to:
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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)