LTP库的使用!🐈

LTP库的使用

1.安装

1
pip install -U ltp ltp-core ltp-extension -i https://pypi.org/simple

2.本地模型调用

从huggingface下载模型后保存在本地。用下述代码进行本地调用。

1
ltp = LTP("D:/Python/MimicSolver/conf/model/LTP_Base1")

3.应用举例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import torch
from ltp import LTP

ltp = LTP("LTP/small") # 默认加载 Small 模型

# 将模型移动到 GPU 上
if torch.cuda.is_available():
# ltp.cuda()
ltp.to("cuda")

output = ltp.pipeline(["他叫汤姆去拿外衣。"], tasks=["cws", "pos", "ner", "srl", "dep", "sdp"])
# 使用字典格式作为返回结果
print(output.cws) # print(output[0]) / print(output['cws']) # 也可以使用下标访问
print(output.pos)
print(output.sdp)
print(output.ner)

# 使用感知机算法实现的分词、词性和命名实体识别,速度比较快,但是精度略低
ltp = LTP("LTP/legacy")
# cws, pos, ner = ltp.pipeline(["他叫汤姆去拿外衣。"], tasks=["cws", "ner"]).to_tuple() # error: NER 需要 词性标注任务的结果
cws, pos, ner = ltp.pipeline(["他叫汤姆去拿外衣。"], tasks=["cws", "pos", "ner"]).to_tuple() # to tuple 可以自动转换为元组格式
# 使用元组格式作为返回结果
print(cws, pos, ner)

tips:

分词 cws、词性 pos、命名实体标注 ner、语义角色标注 srl、依存句法分析 dep、语义依存分析树 sdp、语义依存分析图 sdpg

输出结果:

1
2
3
4
[['他', '叫', '汤姆', '去', '拿', '外衣', '。']]
[['r', 'v', 'nh', 'v', 'v', 'n', 'wp']]
[{'head': [2, 0, 2, 2, 4, 5, 5], 'label': ['AGT', 'Root', 'DATV', 'eSUCC', 'eSUCC', 'PAT', 'mPUNC']}]
[[('Nh', '汤姆')]]

LTP库的使用!🐈
https://yangchuanzhi20.github.io/2024/04/03/人工智能/NLP/库的使用/LTP库/
作者
白色很哇塞
发布于
2024年4月3日
许可协议