哈工大开源工具PyLTP的使用方法

1.安装方法
(1) pip install pyltp 首先 pip 安装 pyltp 库。

(2) 在 LTP 的模型页面下载模型,我直接就放在pyltp库下面了。

下面上代码:

import torch
from ltp import LTP

# 默认 huggingface 下载,可能需要代理

ltp = LTP(r"D:\Python3.8\Lib\site-packages\ltp\LTP_model")  # 默认加载 Small 模型
                        # 也可以传入模型的路径,ltp = LTP("/path/to/your/model")
                        # /path/to/your/model 应当存在 config.json 和其他模型文件
# 将模型移动到 GPU 上
if torch.cuda.is_available():
    # ltp.cuda()
    ltp.to("cuda")
# 自定义词表
ltp.add_word("张三", freq=2)
ltp.add_words(["李四"], freq=2)

#  分词 cws、词性 pos、命名实体标注 ner、语义角色标注 srl、依存句法分析 dep、语义依存分析树 sdp、语义依存分析图 sdpg
output = ltp.pipeline(["张三和李四在2019年3月23日在北京的腾讯技术有限公司一起开会。"], tasks=["cws", "pos", "ner", "srl", "dep", "sdp", "sdpg"])
# 使用字典格式作为返回结果
print('分词结果{}:'.format(output.cws))  # print(output[0]) / print(output['cws']) # 也可以使用下标访问
print('词性标注结果:{}'.format(output.pos))
print('命名实体识别结果:{}'.format(output.ner))
print('语义角色标注结果{}:'.format(output.srl))
print('依存句法分析{}:'.format(output.dep))
print('语义依存分析树{}:'.format(output.sdp))
print('语义依存分析图{}:'.format(output.sdpg))

# 使用感知机算法实现的分词、词性和命名实体识别,速度比较快,但是精度略低
# ltp = LTP("LTP/legacy")
# cws, pos, ner = ltp.pipeline(["张三和李四在2019年3月23日在北京的腾讯技术有限公司一起开会。"], tasks=["cws", "ner"]).to_tuple() # error: NER 需要 词性标注任务的结果

# cws, pos, ner = ltp.pipeline(["张三和李四在2019年3月23日在北京的腾讯技术有限公司一起开会。"], tasks=["cws", "pos", "ner"]).to_tuple()  # to tuple 可以自动转换为元组格式
# 使用元组格式作为返回结果
# print(cws, pos, ner)

output:哈工大开源工具PyLTP的使用方法_第1张图片

你可能感兴趣的:(nlp,python)