我有以下代码:
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,在open opener = self._opener中)
文件“ C:\ Users **** \ AppData \ Local \ Continuum \ miniconda3 \ lib \ pathlib.py”,行1037,在_opener中返回self._accessor.open(self,标志,模式)
文件“ C:\ Users **** \ AppData \ Local \ Continuum \ miniconda3 \ lib \ pathlib.py”,包装的返回strfunc(str(pathobj),* args),行387 FileNotFoundError:[Errno 2]没有这样的文件文件或目录:“ \ images \ dependency_plot.svg”
该目录确实存在,因此我不太确定自己在做什么错。我还查看了spacy用法页面https://spacy.io/usage/visualizers#jupyter,无法弄清楚我在做什么错。我正在使用spyder(如果需要此信息)。请协助。
我认为您那里有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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句