40

中文分词工具之哈工大LTP

 4 years ago
source link: https://www.biaodianfu.com/pyltp.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

LTP是哈工大出品的自然语言处理工具箱, LTP提供了一系列中文自然语言处理工具,用户可以使用这些工具对于中文文本进行分词、词性标注、句法分析等等工作。pyltp是python下对ltp(c++)的封装。

Pyltp在linux环境下安装非常的简单,仅需执行pip install pyltp 即可,但由于需要编译ltp,在Windows环境下安装确存在各种问题。这里采用的是从网上找到的编译好的.whl文件。

pip install ./pyltp-0.2.1-cp36-cp36m-win_amd64.whl

安装完毕后,还需要下载模型文件,文件下载地址: http://ltp.ai/download.html

使用示例:

import os
from pyltp import SentenceSplitter
from pyltp import Segmentor
from pyltp import Postagger
from pyltp import NamedEntityRecognizer
from pyltp import Parser
from pyltp import SementicRoleLabeller
 
LTP_DATA_DIR = 'D:\CodeHub\CutSeg\ltp_data_v3.4.0'  # ltp模型目录的路径
 
# 分句
sents = SentenceSplitter.split('元芳你怎么看?我就趴窗口上看呗!')  # 分句
print('\n'.join(sents))
 
# 分词
cws_model_path = os.path.join(LTP_DATA_DIR, 'cws.model')  # 分词模型路径,模型名称为`cws.model`
segmentor = Segmentor()  # 初始化实例
segmentor.load(cws_model_path)  # 加载模型
words = segmentor.segment('元芳你怎么看')  # 分词
print('/'.join(words))
segmentor.release()  # 释放模型
 
# 词性标注
pos_model_path = os.path.join(LTP_DATA_DIR, 'pos.model')  # 词性标注模型路径,模型名称为`pos.model`
postagger = Postagger()  # 初始化实例
postagger.load(pos_model_path)  # 加载模型
postags = postagger.postag(words)  # 词性标注
print('/'.join(postags))
postagger.release()  # 释放模型
 
# 命名实体识别
ner_model_path = os.path.join(LTP_DATA_DIR, 'ner.model')  # 命名实体识别模型路径,模型名称为`ner.model`
recognizer = NamedEntityRecognizer()  # 初始化实例
recognizer.load(ner_model_path)  # 加载模型
netags = recognizer.recognize(words, postags)  # 命名实体识别
print('/'.join(netags))
recognizer.release()  # 释放模型
 
# 依存句法分析
par_model_path = os.path.join(LTP_DATA_DIR, 'parser.model')  # 依存句法分析模型路径,模型名称为`parser.model`
parser = Parser()  # 初始化实例
parser.load(par_model_path)  # 加载模型
arcs = parser.parse(words, postags)  # 句法分析
print("/".join("%d:%s" % (arc.head, arc.relation) for arc in arcs))
parser.release()  # 释放模型
 
# 语义角色标注
# srl_model_path = os.path.join(LTP_DATA_DIR, 'pisrl.model')  # 语义角色标注模型目录路径,模型目录为`pisrl.model`
srl_model_path = os.path.join(LTP_DATA_DIR,
                              'pisrl_win.model')  # windows系统要用不同的SRL模型文件,http://ospm9rsnd.bkt.clouddn.com/server/3.4.0/pisrl_win.model或http://model.scir.yunfutech.com/server/3.4.0/pisrl_win.model
labeller = SementicRoleLabeller()  # 初始化实例
labeller.load(srl_model_path)  # 加载模型
roles = labeller.label(words, postags, arcs)  # 语义角色标注
for role in roles:
    print(role.index, "".join(
        ["%s:(%d,%d)" % (arg.name, arg.range.start, arg.range.end) for arg in role.arguments]))
labeller.release()  # 释放模型

参考链接:


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK