天天看點

中文依存句法結構分析

#!/usr/bin/python3
# -*- coding:utf-8 -*-

"""
@Author  : heyw
@Time    : 2020/1/14 10:34
@Software: PyCharm
@File    : stanford.py
"""
from stanfordcorenlp import StanfordCoreNLP
from nltk.tree import Tree

# 模型下載下傳位址:https://nlp.stanford.edu/software/corenlp-backup-download.html
# 筆者将模型放置于AIAPP目錄下,并将模型檔案夾改名為stanfordnlp
nlp = StanfordCoreNLP(r'C:\AIAPP\stanfordnlp', lang='zh') # 英文使用 

sentence = "我愛北京天安門。"

# 分詞
print("分詞:", nlp.word_tokenize(sentence))
# 詞性标注
print("詞性标注:", nlp.pos_tag(sentence))
# 依存分析
print("依存分析:", nlp.dependency_parse(sentence))
# 句法樹解析
print("句子解析:\n", nlp.parse(sentence))
# 生成節點關系清單
tree = Tree.fromstring(nlp.parse(sentence))
print("節點關系:",tree.productions())
# 繪制句法樹
tree.draw()
           
分詞: ['我愛', '北京', '天安門', '。']
詞性标注: [('我愛', 'VV'), ('北京', 'NR'), ('天安門', 'NR'), ('。', 'PU')]
依存分析: [('ROOT', 0, 1), ('name', 3, 2), ('dobj', 1, 3), ('punct', 1, 4)]
句子解析:
 (ROOT
  (IP
    (VP (VV 我愛)
      (NP (NR 北京) (NR 天安門)))
    (PU 。)))
節點關系: [ROOT -> IP, IP -> VP PU, VP -> VV NP, VV -> '我愛', NP -> NR NR, NR -> '北京', NR -> '天安門', PU -> '。']
           
中文依存句法結構分析