最近在使用Stanfordcorenlp构建依存树,但目前该工具需要在Java环境下才可以运行,所以建议在系统上提前安装好Java环境。在这里介绍一下如何使用python来调用Stanfordcorenlp
一、下载与安装
-
由于在Windows系统上,有Stanfordcorenlp包可以使用,可以直接在环境下安装对应的python包
pip install stanfordcorenlp
-
安装好对应的包,还需要下载Stanfordcorenlp的安装包。(安装包分为不同的语言,可按照自己的需求选择),下载后,解压到一个文件夹内。
配置好所有环境之后,就可以使用Stanfordcorenlp的众多功能了(分词,词性标注,依存生成等等。)
二、使用
通过下面的函数我们可以得到句子的依存关系,可是无法得到词语与依存关系的对应。
from stanfordcorenlp import StanfordCoreNLP
from graphviz import Digraph
nlp_zh = StanfordCoreNLP(r'..\stanford-corenlp-4.3.0', lang=language) # 导入解压之后的路径
sentence = '生成依存语法树'
depend = list(nlp_zh.dependency_parse(sentence)) # 依存关系
words = list(nlp_zh.word_tokenize(sentence)) # 分词
print(depend)
print(words)
# [('ROOT', 0, 1), ('compound:vc', 1, 2), ('dobj', 1, 3)]
# ['生成', '依存', '语法树']
这里我们要将单词与依存关系对应起来。
dependency_tree.sort(key=lambda x: x[2]) # 排序
words = [w + "-" + str(idx) for idx, w in enumerate(words)]
rely_id = [arc[1] for arc in dependency_tree] # 依存ID
relation = [arc[0] for arc in dependency_tree] # 依存语法
heads = ['Root' if id == 0 else words[id - 1] for id in rely_id]
# 输出匹配单词的依存树
for i in range(len(words)):
print(relation[i] + '(' + words[i] + ', ' + heads[i] + ')')
"""
ROOT(生成-0, Root)
compound:vc(依存-1, 生成-0)
dobj(语法树-2, 生成-0)
"""
可视化之前,需要先安装graphviz包。
pip install graphviz
最后将依存树可视化。
# 将依存树保存为jpg图片
g = Digraph("demo1", format="jpg")
# 节点定义
g.node(name='Root', fontname="SimSun", shape='doublecircle')
for word in words:
g.node(name=word, fontname="SimSun", label=word.split("-")[0])
# 设置图节点
for i in range(len(words)):
if relation[i] not in ['HED']:
g.edge(heads[i], words[i], label=relation[i])
else:
if heads[i] == 'Root':
g.edge('Root', words[i], label=relation[i])
else:
g.edge('Root', heads[i], label=relation[i])
g.render(cleanup=True)
生成的图片如下图:
完整的代码如下:
from stanfordcorenlp import StanfordCoreNLP
from graphviz import Digraph
def dependency(sentence, language='zh'):
"""
使用Stanfordcorenlp构建依存树
:param sentence: 需要构建树的句子
:param language: 支持的语言
:return: 依存序列
"""
nlp_zh = StanfordCoreNLP('..\stanford-corenlp-4.3.0', lang=language) # 导入解压之后的路径
words = list(nlp_zh.word_tokenize(sentence)) # 分词
depend = list(nlp_zh.dependency_parse(sentence)) # 依存关系
return depend, words
def Dependency_tree_visualization(dependency_tree, words):
"""
将依存序列与对应的单词进行匹配,并将依存树可视化,最终将依存树图片保存为jpg
:param dependency_tree: 依存树序列
:param words: 经过
:return:
"""
dependency_tree.sort(key=lambda x: x[2]) # 排序
words = [w + "-" + str(idx) for idx, w in enumerate(words)]
rely_id = [arc[1] for arc in dependency_tree] # 依存ID
relation = [arc[0] for arc in dependency_tree] # 依存语法
heads = ['Root' if id == 0 else words[id - 1] for id in rely_id]
# 输出匹配单词的依存树
for i in range(len(words)):
print(relation[i] + '(' + words[i] + ', ' + heads[i] + ')')
# 将依存树保存为jpg图片
g = Digraph("Dependency_tree", format="jpg")
# 节点定义
g.node(name='Root', fontname="SimSun", shape='doublecircle')
for word in words:
g.node(name=word, fontname="SimSun", label=word.split("-")[0])
# 设置图节点
for i in range(len(words)):
if relation[i] not in ['HED']:
g.edge(heads[i], words[i], label=relation[i])
else:
if heads[i] == 'Root':
g.edge('Root', words[i], label=relation[i])
else:
g.edge('Root', heads[i], label=relation[i])
g.render(cleanup=True)
if __name__ == ("__main__"):
sentence = "生成依存语法树"
de_line, word = dependency(sentence)
Dependency_tree_visualization(de_line, word)
print(de_line)
print(word)