我有以下代码:
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行,处于打开状态 opener = self._opener)
文件 “ C:\ Users **** \ AppData \ Local \ Continuum \ miniconda3 \ lib \ pathlib.py”, _opener中的第1037行 返回self._accessor.open(self,标志,模式)
文件 “ C:\ Users **** \ AppData \ Local \ Continuum \ miniconda3 \ lib \ pathlib.py”, 387号线,缠绕 返回strfunc(str(pathobj),* args) FileNotFoundError:[错误2]没有这样的文件或目录: '\ images \ dependency_plot.svg'
该目录确实存在,所以我不太确定自己在做什么错。我还查看了spacy用法页面https://spacy.io/usage/visualizers#jupyter,无法弄清楚我在做什么错。我正在使用spyder(如果需要此信息)。 请协助。
答案 0 :(得分:1)
我认为您那里有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)
答案 1 :(得分:0)
我按照@Petr Matuska 的回答,遇到了每个人都在评论的错误。在调试时,我发现了 SpaCy documentation 中也提到的两个问题。
jupyter=False
树作为 SVG。这样你就不会在 Jupyter 上看到输出,但你
可以打开保存的文件查看结果。重要说明 由于每个可视化都是作为单独的 SVG,导出 .svg 文件仅适用于渲染单个文件 一次医生。 (这是有道理的——毕竟,每个可视化 应该是一个独立的图形。)所以而不是在 一,遍历它们并分别导出。
sentences = ["This is an example."]
。这是直接来自 SpaCy documentation 的代码片段,非常适合我。
import spacy
from spacy import displacy
from pathlib import Path
nlp = spacy.load("en_core_web_sm")
sentences = ["This is an example.", "This is another one."]
for sent in sentences:
doc = nlp(sent)
svg = displacy.render(doc, style="dep", jupyter=False)
file_name = '-'.join([w.text for w in doc if not w.is_punct]) + ".svg"
output_path = Path("/images/" + file_name)
output_path.open("w", encoding="utf-8").write(svg)