I have the following code:
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)
I am trying to write an the rendered file to an svg file in the images folder. However, I get the error:
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'
The directory does exist and so I'm not really sure what I'm doing wrong. I have also looked at the spacy usage page https://spacy.io/usage/visualizers#jupyter and couldn't figure out what I'm doing wrong. I'm using spyder (if this information is required). Please assist.
A modern syntactic dependency visualizer. Visualize spaCy's guess at the syntactic structure of a sentence. Arrows point from children to heads, and are labelled by their relation type. View more.
displaCy is able to detect whether you're working in a Jupyter notebook, and will return markup that can be rendered in a cell straight away. When you export your notebook, the visualizations will be included as HTML.
This displaCy method will render a dependency parse tree or named entity visualization. It represents the document to visualize. We have two visualization style namely 'dep', or 'ent'. The default value is 'dep'.
I think that you have 2 errors there. First you should fix your path - add "."
from:
output_path = Path("/images/dependency_plot.svg")
to:
output_path = Path("./images/dependency_plot.svg")
The second error is in this line
svg = displacy.render(sentence_nlp, style="dep", jupyter=True)
I think you need to remove jupyter=True
to be able to write it in the svg file. Otherwise you will be given error like TypeError: write() argument must be str, not None
This works for me:
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With