Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When I save the output of displacy.render(doc, style="dep") to a svg file, there is a TypeError: write() argument must be str, not None

Tags:

python

spacy

I want to save the visualisation of spaCy with the code that spaCy offers here : https://spacy.io/usage/visualizers

Here is my code :

nlp = spacy.load("en_core_web_sm")
doc = nlp(u"Autonomous cars shift insurance liability toward manufacturers")
svg = spacy.displacy.render(doc, style="dep")
output_path = Path(os.path.join("./", "sentence.svg"))
output_path.open('w', encoding="utf-8").write(svg)

But when I execute this code, there is an error : TypeError: write() argument must be str, not None

So how can I save the output of spacy.displacy.render ? How can I fix this error ?

like image 904
mm666 Avatar asked Apr 17 '19 09:04

mm666


1 Answers

The code provided in the question works fine, when executed in an IDE like PyCharm.

However, displacy.render() works slightly differently in a Jupyter notebook, cf the documentation here and here:

If you’re running a Jupyter notebook, displaCy will detect this and return the markup in a format ready to be rendered and exported.

You can overwrite this automated detection by explicitly setting jupyter=False in the render() call.

like image 122
Sofie VL Avatar answered Nov 15 '22 04:11

Sofie VL