python - 当我将 displacy.render(doc, style ="dep") 的输出保存到 svg 文件时,出现 TypeError : write() argument must be str, not None

标签 python spacy

我想使用 spaCy 在这里提供的代码保存 spaCy 的可视化效果:https://spacy.io/usage/visualizers

这是我的代码:

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)

但是当我执行此代码时,出现错误:TypeError: write() argument must be str, not None

那么如何保存 spacy.displace.render 的输出?我该如何修复这个错误?

最佳答案

问题中提供的代码在 PyCharm 等 IDE 中执行时工作正常。

但是,displacy.render() 在 Jupyter 笔记本中的工作方式略有不同,请参见文档 herehere :

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

您可以通过在 render() 调用中显式设置 jupyter=False 来覆盖此自动检测。

关于python - 当我将 displacy.render(doc, style ="dep") 的输出保存到 svg 文件时,出现 TypeError : write() argument must be str, not None,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55723812/

相关文章:

python - SpaCy 中的 .pos_ 在 Python 中不返回任何结果

python-3.x - 使用 Spacy 进行命名实体识别的交叉验证

python - 如何使用 SpaCy 从句子列表中获取名词短语

python - 添加 numpy 时破坏了我的 python 构建

python - CrawlSpider 仅获取第一页中匹配链接的子集,然后移动到抓取第二页中的链接

python - 如何让我的 setup.py 使用文件的相对路径?

python - 将多列从行旋转到列

python - 在异常时覆盖 django-rest-framework 中接受的渲染器

python - Spacy NER - 训练仅具有实体集合的模型

python - 无法加载 spaCy 模型 'en_core_web_sm'