pythonspacydependency-parsing

Save SpaCy render file as SVG using DisplaCy


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.


Solution

  • 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)