Python 实现语句中提取人名(附代码) | Python工具

前言

本文提供了一种在报表中提取人名的工具方法,可以直接使用。

[En]

This article provides a tool method to extract the name of a person in a statement, which can be used directly.

环境依赖

需要安装两个库,其实一个就可以了,不过我已经准备了两个库做个比较。

[En]

Need to install two libraries, in fact, one is fine, but I have prepared two libraries to make a comparison.

安装命令如下:

pip install LAC -i https://pypi.douban.com/simple
pip install ltp -i https://pypi.douban.com/simple

代码

不废话,上代码。

#!/user/bin/env python
coding=utf-8
"""
@project : csdn
@author  : 剑客阿良_ALiang
@file   : extract_sentence_name_tool.py
@ide    : PyCharm
@time   : 2022-01-25 11:11:43
"""
from LAC import LAC
from ltp import LTP
import time

lac = LAC(mode="lac")
ltp = LTP()

句子提取名字
def extract_name(sentence: str, type='lac'):
    user_name_lis = []
    if type == 'lac':
        _result = lac.run(sentence)
        for _index, _label in enumerate(_result[1]):
            if _label == "PER":
                user_name_lis.append(_result[0][_index])
    elif type == 'ltp':
        _seg, _hidden = ltp.seg([sentence])
        _pos_hidden = ltp.pos(_hidden)
        for _seg_i, _seg_v in enumerate(_seg):
            _hidden_v = _pos_hidden[_seg_i]
            for _h_i, _h_v in enumerate(_hidden_v):
                if _h_v == "nh":
                    user_name_lis.append(_seg_v[_h_i])
    else:
        raise Exception('type not suppose')
    return user_name_lis

if __name__ == '__main__':
    _start_lac = time.time()
    lis1 = extract_name("就因为看了沈腾和贾玲的王牌对王牌节目,所以杨迪肯定偷题了。", 'lac')
    _end_lac = time.time()
    print("LAC: {}

代码说明:

1、extract_name方法入参分别为:语句参数、类型参数。其中默认为lac模式,可以选择ltp模式。

其中lac模型提取人名的速率较快,但是ltp的提取人名准确率更高。

验证并执行它,以查看效率。

[En]

Verify it and execute it to see the efficiency.

Python 实现语句中提取人名(附代码) | Python工具

总结

使用的时候可以多试试两个库的区别,ltp的准确率稍微高一点。

分享:每个人的眼睛都睁开了,但这并不意味着每个人都在看世界。许多人几乎不需要自己的眼睛就能看到。他们只听别人说,他们看到的世界总是别人说的。–猜猜。

[En]

Share: everyone’s eyes are open, but it doesn’t mean that everyone is looking at the world. Many people hardly need their own eyes to see. They only listen to others say that the world they see is always what others say. — guess.

如果这篇文章对你有帮助,请点击它,谢谢!

[En]

If this article is helpful to you, click on it, thank you!

Python 实现语句中提取人名(附代码) | Python工具

本人CSDN主页地址:剑客阿良_ALiang的主页

一起学习,一起进步。

Original: https://www.cnblogs.com/jk-aliang/p/15843223.html
Author: 剑客·阿良
Title: Python 实现语句中提取人名(附代码) | Python工具

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/510144/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球