Python 自然语言处理 命名 实体识别

版权声明:欢迎分享和转载,请注明出处 shuihupo:https://blog.csdn.net/shuihupo.同时,本博客部分会在云南省高校数据化运营管理工程中心博客同步。欢迎沟通交流:[email protected] https://blog.csdn.net/shuihupo/article/details/81541334

NER系统的构建与评估:

1.将文档分割成句子

2.将句子分割为单词

3.标记每个单词的词性

4.从标记单词集中识别出命名实体

5.识别每个命名实体的分类

6.评估

NLTK(Natural Language Toolkit)自然语言处理工具包,在NLP领域中,比较常用的一个Python库。它提供了易于使用的接口,通过这些接口可以访问超过50个语料库和词汇资源(如WordNet),还有一套用于分类、标记化、词干标记、解析和语义推理的文本处理库,以及工业级NLP库的封装器和一个活跃的讨论论坛。

官方文档:http://www.nltk.org
python安装与测试NLTK链接:https://blog.csdn.net/shuihupo/article/details/79635044
百度api自然语言处理的调用 :https://blog.csdn.net/m0_37788308/article/details/79994499

基于NLTK的命名实体识别:

读入英文文本数据

# -*- coding: utf-8 -*- 
import nltk  
import pprint
# filename = "test.txt"
# with open(filename, 'r', encoding='utf8') as sampleFile:
#     text=sampleFile.read()

减少迁移带来的文本路径问题,我们将文本存为变量

text = "Mexico quakes with joy over World Cup upset win.Mexico’s Earthquake Early Warning and Monitoring System issued a message on the 17th that the Mexican team played against the German team in the World Cup. During the first half of the game until the 35th minute, the Mexican team striker Losano broke the deadlock and scored the first goal, scoring a goal in Mexico. The city monitored minor earthquakes. This monitoring system analyzes that the earthquake was caused by man-made methods or caused by many people excitedly jumping when scoring."
en = {} 

1.将文档分割成句子
2.将句子分割为单词
3.标记每个单词的词性

tokenized = nltk.word_tokenize(text) #分词  
# pprint.pprint(tokenized)
tagged = nltk.pos_tag(tokenized)         #词性标注 
#pprint.pprint(tagged)
chunked = nltk.ne_chunk(tagged)          #命名实体识别 

NN 名词 year,home, costs, time, education

NNS 名词复数 undergraduates scotches

NNP 专有名词 Alison,Africa,April,Washington

NNPS 专有名词复数 Americans Americas Amharas Amityvilles

#pprint.pprint(chunked)# <class 'nltk.tree.Tree'>
print(chunked.draw())
None
要注意对树的处理,观察树的形式
for tree in chunked:
    # print(tree)
    # print(type(tree)) 非专有名词为'tuple',是专有名词的为“tree”
    if hasattr(tree, 'label'):
        #print(tree.draw())
        ne = ' '.join(c[0] for c in tree.leaves())
        en[ne] = [tree.label(), ' '.join(c[1] for c in tree.leaves())]
for key in en.keys():
    print(key, ':', en[key])
Mexican : ['GPE', 'NNP']
Early Warning : ['PERSON', 'JJ NNP']
German : ['GPE', 'JJ']
Monitoring System : ['ORGANIZATION', 'NNP NNP']
Mexico : ['GPE', 'NNP']
Losano : ['PERSON', 'NNP']

百度API实现

textnew= "世界杯爆冷门,墨西哥球迷激动跳跃引发首都墨西哥城地震!墨西哥地震预警监控系统17日发布消息,当天墨西哥队在对阵德国队的世界杯比赛中,上半场比赛进行至第35分钟时,墨西哥队前锋洛萨诺打破僵局攻入首球,进球时墨西哥城监测到轻微地震。这一监控系统分析说,这次地震是由人为方式引发,或因进球时许多民众激动跳跃造成。"
# -*- coding: utf-8 -*-
import urllib3
import json
import urllib.request 
import pprint

第一步:获取access_token
client_id 为官网获取的AK, client_secret 为官网获取的SK

access_token ="24.340837cdde292a61442507b60e6fb64c.2592000.1532060546.282335-11012308"

第二步:post请求调用API,传入参数

import sys
print(sys.getdefaultencoding())
http=urllib3.PoolManager()
url = "https://aip.baidubce.com/rpc/2.0/nlp/v1/lexer?access_token="+access_token
print(url)
data ={"text":textnew}
utf-8
https://aip.baidubce.com/rpc/2.0/nlp/v1/lexer?access_token=24.340837cdde292a61442507b60e6fb64c.2592000.1532060546.282335-11012308
encode_data= json.dumps(data).encode('GBK') #传入数据是字典,需要编码
#JSON:在发起请求时,可以通过定义body 参数并定义headers的Content-Type参数来发送一个已经过编译的JSON数据:
request = http.request('POST',
                       url,
                       body=encode_data,
                       headers={'Content-Type':'application/json'}
                       )
result = str(request.data,'GBK')
D:\local\Anaconda3\lib\site-packages\urllib3\connectionpool.py:858: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
  InsecureRequestWarning)
result_dir = eval(result)
pprint.pprint(result_dir)
{'items': [{'basic_words': ['世界', '杯'],
            'byte_length': 6,
            'byte_offset': 0,
            'formal': '',
            'item': '世界杯',
            'loc_details': [],
            'ne': '',
            'pos': 'nz',
            'uri': ''},
           {'basic_words': ['爆冷', '门'],
            'byte_length': 6,
            'byte_offset': 6,
            'formal': '',
            'item': '爆冷门',
            'loc_details': [],
            'ne': '',
            'pos': 'nz',
            'uri': ''},
           {'basic_words': [','],
            'byte_length': 2,
            'byte_offset': 12,
            'formal': '',
            'item': ',',
            'loc_details': [],
            'ne': '',
            'pos': 'w',
            'uri': ''},
           {'basic_words': ['墨西哥'],
            'byte_length': 6,
            'byte_offset': 14,
            'formal': '',
            'item': '墨西哥',
            'loc_details': [],
            'ne': 'LOC',
            'pos': '',
            'uri': ''},
           {'basic_words': ['球迷'],
            'byte_length': 4,
            'byte_offset': 20,
            'formal': '',
            'item': '球迷',
            'loc_details': [],
            'ne': '',
            'pos': 'n',
            'uri': ''},
           {'basic_words': ['激动'],
            'byte_length': 4,
            'byte_offset': 24,
            'formal': '',
            'item': '激动',
            'loc_details': [],
            'ne': '',
            'pos': 'a',
            'uri': ''},
           {'basic_words': ['跳跃'],
            'byte_length': 4,
            'byte_offset': 28,
            'formal': '',
            'item': '跳跃',
            'loc_details': [],
            'ne': '',
            'pos': 'vn',
            'uri': ''},
           {'basic_words': ['引发'],
            'byte_length': 4,
            'byte_offset': 32,
            'formal': '',
            'item': '引发',
            'loc_details': [],
            'ne': '',
            'pos': 'v',
            'uri': ''},
           {'basic_words': ['首都'],
            'byte_length': 4,
            'byte_offset': 36,
            'formal': '',
            'item': '首都',
            'loc_details': [],
            'ne': '',
            'pos': 'n',
            'uri': ''},
           {'basic_words': ['墨西哥', '城'],
            'byte_length': 8,
            'byte_offset': 40,
            'formal': '',
            'item': '墨西哥城',
            'loc_details': [],
            'ne': 'LOC',
            'pos': '',
            'uri': ''},
           {'basic_words': ['地震'],
            'byte_length': 4,
            'byte_offset': 48,
            'formal': '',
            'item': '地震',
            'loc_details': [],
            'ne': '',
            'pos': 'n',
            'uri': ''},
           {'basic_words': ['!'],
            'byte_length': 2,
            'byte_offset': 52,
            'formal': '',
            'item': '!',
            'loc_details': [],
            'ne': '',
            'pos': 'w',
            'uri': ''},
           {'basic_words': ['墨西哥'],
            'byte_length': 6,
            'byte_offset': 54,
            'formal': '',
            'item': '墨西哥',
            'loc_details': [],
            'ne': 'LOC',
            'pos': '',
            'uri': ''},
           {'basic_words': ['地震'],
            'byte_length': 4,
            'byte_offset': 60,
            'formal': '',
            'item': '地震',
            'loc_details': [],
            'ne': '',
            'pos': 'n',
            'uri': ''},
           {'basic_words': ['预警'],
            'byte_length': 4,
            'byte_offset': 64,
            'formal': '',
            'item': '预警',
            'loc_details': [],
            'ne': '',
            'pos': 'vn',
            'uri': ''},
           {'basic_words': ['监控'],
            'byte_length': 4,
            'byte_offset': 68,
            'formal': '',
            'item': '监控',
            'loc_details': [],
            'ne': '',
            'pos': 'vn',
            'uri': ''},
           {'basic_words': ['系统'],
            'byte_length': 4,
            'byte_offset': 72,
            'formal': '',
            'item': '系统',
            'loc_details': [],
            'ne': '',
            'pos': 'n',
            'uri': ''},
           {'basic_words': ['17', '日'],
            'byte_length': 4,
            'byte_offset': 76,
            'formal': '',
            'item': '17日',
            'loc_details': [],
            'ne': 'TIME',
            'pos': '',
            'uri': ''},
           {'basic_words': ['发布'],
            'byte_length': 4,
            'byte_offset': 80,
            'formal': '',
            'item': '发布',
            'loc_details': [],
            'ne': '',
            'pos': 'v',
            'uri': ''},
           {'basic_words': ['消息'],
            'byte_length': 4,
            'byte_offset': 84,
            'formal': '',
            'item': '消息',
            'loc_details': [],
            'ne': '',
            'pos': 'n',
            'uri': ''},
           {'basic_words': [','],
            'byte_length': 2,
            'byte_offset': 88,
            'formal': '',
            'item': ',',
            'loc_details': [],
            'ne': '',
            'pos': 'w',
            'uri': ''},
           {'basic_words': ['当天'],
            'byte_length': 4,
            'byte_offset': 90,
            'formal': '',
            'item': '当天',
            'loc_details': [],
            'ne': 'TIME',
            'pos': '',
            'uri': ''},
           {'basic_words': ['墨西哥', '队'],
            'byte_length': 8,
            'byte_offset': 94,
            'formal': '',
            'item': '墨西哥队',
            'loc_details': [],
            'ne': 'ORG',
            'pos': '',
            'uri': ''},
           {'basic_words': ['在'],
            'byte_length': 2,
            'byte_offset': 102,
            'formal': '',
            'item': '在',
            'loc_details': [],
            'ne': '',
            'pos': 'p',
            'uri': ''},
           {'basic_words': ['对阵'],
            'byte_length': 4,
            'byte_offset': 104,
            'formal': '',
            'item': '对阵',
            'loc_details': [],
            'ne': '',
            'pos': 'v',
            'uri': ''},
           {'basic_words': ['德国', '队'],
            'byte_length': 6,
            'byte_offset': 108,
            'formal': '',
            'item': '德国队',
            'loc_details': [],
            'ne': 'ORG',
            'pos': '',
            'uri': ''},
           {'basic_words': ['的'],
            'byte_length': 2,
            'byte_offset': 114,
            'formal': '',
            'item': '的',
            'loc_details': [],
            'ne': '',
            'pos': 'u',
            'uri': ''},
           {'basic_words': ['世界', '杯'],
            'byte_length': 6,
            'byte_offset': 116,
            'formal': '',
            'item': '世界杯',
            'loc_details': [],
            'ne': '',
            'pos': 'nz',
            'uri': ''},
           {'basic_words': ['比赛'],
            'byte_length': 4,
            'byte_offset': 122,
            'formal': '',
            'item': '比赛',
            'loc_details': [],
            'ne': '',
            'pos': 'vn',
            'uri': ''},
           {'basic_words': ['中'],
            'byte_length': 2,
            'byte_offset': 126,
            'formal': '',
            'item': '中',
            'loc_details': [],
            'ne': '',
            'pos': 'f',
            'uri': ''},
           {'basic_words': [','],
            'byte_length': 2,
            'byte_offset': 128,
            'formal': '',
            'item': ',',
            'loc_details': [],
            'ne': '',
            'pos': 'w',
            'uri': ''},
           {'basic_words': ['上', '半场'],
            'byte_length': 6,
            'byte_offset': 130,
            'formal': '',
            'item': '上半场',
            'loc_details': [],
            'ne': 'TIME',
            'pos': '',
            'uri': ''},
           {'basic_words': ['比赛'],
            'byte_length': 4,
            'byte_offset': 136,
            'formal': '',
            'item': '比赛',
            'loc_details': [],
            'ne': '',
            'pos': 'vn',
            'uri': ''},
           {'basic_words': ['进行'],
            'byte_length': 4,
            'byte_offset': 140,
            'formal': '',
            'item': '进行',
            'loc_details': [],
            'ne': '',
            'pos': 'v',
            'uri': ''},
           {'basic_words': ['至'],
            'byte_length': 2,
            'byte_offset': 144,
            'formal': '',
            'item': '至',
            'loc_details': [],
            'ne': '',
            'pos': 'p',
            'uri': ''},
           {'basic_words': ['第', '35', '分钟'],
            'byte_length': 8,
            'byte_offset': 146,
            'formal': '',
            'item': '第35分钟',
            'loc_details': [],
            'ne': 'TIME',
            'pos': '',
            'uri': ''},
           {'basic_words': ['时'],
            'byte_length': 2,
            'byte_offset': 154,
            'formal': '',
            'item': '时',
            'loc_details': [],
            'ne': '',
            'pos': 'n',
            'uri': ''},
           {'basic_words': [','],
            'byte_length': 2,
            'byte_offset': 156,
            'formal': '',
            'item': ',',
            'loc_details': [],
            'ne': '',
            'pos': 'w',
            'uri': ''},
           {'basic_words': ['墨西哥', '队'],
            'byte_length': 8,
            'byte_offset': 158,
            'formal': '',
            'item': '墨西哥队',
            'loc_details': [],
            'ne': 'ORG',
            'pos': '',
            'uri': ''},
           {'basic_words': ['前锋'],
            'byte_length': 4,
            'byte_offset': 166,
            'formal': '',
            'item': '前锋',
            'loc_details': [],
            'ne': '',
            'pos': 'n',
            'uri': ''},
           {'basic_words': ['洛', '萨诺'],
            'byte_length': 6,
            'byte_offset': 170,
            'formal': '',
            'item': '洛萨诺',
            'loc_details': [],
            'ne': 'PER',
            'pos': '',
            'uri': ''},
           {'basic_words': ['打破'],
            'byte_length': 4,
            'byte_offset': 176,
            'formal': '',
            'item': '打破',
            'loc_details': [],
            'ne': '',
            'pos': 'v',
            'uri': ''},
           {'basic_words': ['僵局'],
            'byte_length': 4,
            'byte_offset': 180,
            'formal': '',
            'item': '僵局',
            'loc_details': [],
            'ne': '',
            'pos': 'n',
            'uri': ''},
           {'basic_words': ['攻入'],
            'byte_length': 4,
            'byte_offset': 184,
            'formal': '',
            'item': '攻入',
            'loc_details': [],
            'ne': '',
            'pos': 'v',
            'uri': ''},
           {'basic_words': ['首'],
            'byte_length': 2,
            'byte_offset': 188,
            'formal': '',
            'item': '首',
            'loc_details': [],
            'ne': '',
            'pos': 'm',
            'uri': ''},
           {'basic_words': ['球'],
            'byte_length': 2,
            'byte_offset': 190,
            'formal': '',
            'item': '球',
            'loc_details': [],
            'ne': '',
            'pos': 'n',
            'uri': ''},
           {'basic_words': [','],
            'byte_length': 2,
            'byte_offset': 192,
            'formal': '',
            'item': ',',
            'loc_details': [],
            'ne': '',
            'pos': 'w',
            'uri': ''},
           {'basic_words': ['进球'],
            'byte_length': 4,
            'byte_offset': 194,
            'formal': '',
            'item': '进球',
            'loc_details': [],
            'ne': '',
            'pos': 'vn',
            'uri': ''},
           {'basic_words': ['时'],
            'byte_length': 2,
            'byte_offset': 198,
            'formal': '',
            'item': '时',
            'loc_details': [],
            'ne': '',
            'pos': 'n',
            'uri': ''},
           {'basic_words': ['墨西哥', '城'],
            'byte_length': 8,
            'byte_offset': 200,
            'formal': '',
            'item': '墨西哥城',
            'loc_details': [],
            'ne': 'LOC',
            'pos': '',
            'uri': ''},
           {'basic_words': ['监测'],
            'byte_length': 4,
            'byte_offset': 208,
            'formal': '',
            'item': '监测',
            'loc_details': [],
            'ne': '',
            'pos': 'v',
            'uri': ''},
           {'basic_words': ['到'],
            'byte_length': 2,
            'byte_offset': 212,
            'formal': '',
            'item': '到',
            'loc_details': [],
            'ne': '',
            'pos': 'v',
            'uri': ''},
           {'basic_words': ['轻微'],
            'byte_length': 4,
            'byte_offset': 214,
            'formal': '',
            'item': '轻微',
            'loc_details': [],
            'ne': '',
            'pos': 'a',
            'uri': ''},
           {'basic_words': ['地震'],
            'byte_length': 4,
            'byte_offset': 218,
            'formal': '',
            'item': '地震',
            'loc_details': [],
            'ne': '',
            'pos': 'n',
            'uri': ''},
           {'basic_words': ['。'],
            'byte_length': 2,
            'byte_offset': 222,
            'formal': '',
            'item': '。',
            'loc_details': [],
            'ne': '',
            'pos': 'w',
            'uri': ''},
           {'basic_words': ['这'],
            'byte_length': 2,
            'byte_offset': 224,
            'formal': '',
            'item': '这',
            'loc_details': [],
            'ne': '',
            'pos': 'r',
            'uri': ''},
           {'basic_words': ['一'],
            'byte_length': 2,
            'byte_offset': 226,
            'formal': '',
            'item': '一',
            'loc_details': [],
            'ne': '',
            'pos': 'm',
            'uri': ''},
           {'basic_words': ['监控'],
            'byte_length': 4,
            'byte_offset': 228,
            'formal': '',
            'item': '监控',
            'loc_details': [],
            'ne': '',
            'pos': 'vn',
            'uri': ''},
           {'basic_words': ['系统'],
            'byte_length': 4,
            'byte_offset': 232,
            'formal': '',
            'item': '系统',
            'loc_details': [],
            'ne': '',
            'pos': 'n',
            'uri': ''},
           {'basic_words': ['分析'],
            'byte_length': 4,
            'byte_offset': 236,
            'formal': '',
            'item': '分析',
            'loc_details': [],
            'ne': '',
            'pos': 'vn',
            'uri': ''},
           {'basic_words': ['说'],
            'byte_length': 2,
            'byte_offset': 240,
            'formal': '',
            'item': '说',
            'loc_details': [],
            'ne': '',
            'pos': 'v',
            'uri': ''},
           {'basic_words': [','],
            'byte_length': 2,
            'byte_offset': 242,
            'formal': '',
            'item': ',',
            'loc_details': [],
            'ne': '',
            'pos': 'w',
            'uri': ''},
           {'basic_words': ['这次'],
            'byte_length': 4,
            'byte_offset': 244,
            'formal': '',
            'item': '这次',
            'loc_details': [],
            'ne': '',
            'pos': 'r',
            'uri': ''},
           {'basic_words': ['地震'],
            'byte_length': 4,
            'byte_offset': 248,
            'formal': '',
            'item': '地震',
            'loc_details': [],
            'ne': '',
            'pos': 'n',
            'uri': ''},
           {'basic_words': ['是'],
            'byte_length': 2,
            'byte_offset': 252,
            'formal': '',
            'item': '是',
            'loc_details': [],
            'ne': '',
            'pos': 'v',
            'uri': ''},
           {'basic_words': ['由'],
            'byte_length': 2,
            'byte_offset': 254,
            'formal': '',
            'item': '由',
            'loc_details': [],
            'ne': '',
            'pos': 'p',
            'uri': ''},
           {'basic_words': ['人为'],
            'byte_length': 4,
            'byte_offset': 256,
            'formal': '',
            'item': '人为',
            'loc_details': [],
            'ne': '',
            'pos': 'a',
            'uri': ''},
           {'basic_words': ['方式'],
            'byte_length': 4,
            'byte_offset': 260,
            'formal': '',
            'item': '方式',
            'loc_details': [],
            'ne': '',
            'pos': 'n',
            'uri': ''},
           {'basic_words': ['引发'],
            'byte_length': 4,
            'byte_offset': 264,
            'formal': '',
            'item': '引发',
            'loc_details': [],
            'ne': '',
            'pos': 'v',
            'uri': ''},
           {'basic_words': [','],
            'byte_length': 2,
            'byte_offset': 268,
            'formal': '',
            'item': ',',
            'loc_details': [],
            'ne': '',
            'pos': 'w',
            'uri': ''},
           {'basic_words': ['或'],
            'byte_length': 2,
            'byte_offset': 270,
            'formal': '',
            'item': '或',
            'loc_details': [],
            'ne': '',
            'pos': 'c',
            'uri': ''},
           {'basic_words': ['因'],
            'byte_length': 2,
            'byte_offset': 272,
            'formal': '',
            'item': '因',
            'loc_details': [],
            'ne': '',
            'pos': 'p',
            'uri': ''},
           {'basic_words': ['进球'],
            'byte_length': 4,
            'byte_offset': 274,
            'formal': '',
            'item': '进球',
            'loc_details': [],
            'ne': '',
            'pos': 'vn',
            'uri': ''},
           {'basic_words': ['时'],
            'byte_length': 2,
            'byte_offset': 278,
            'formal': '',
            'item': '时',
            'loc_details': [],
            'ne': '',
            'pos': 'n',
            'uri': ''},
           {'basic_words': ['许多'],
            'byte_length': 4,
            'byte_offset': 280,
            'formal': '',
            'item': '许多',
            'loc_details': [],
            'ne': '',
            'pos': 'm',
            'uri': ''},
           {'basic_words': ['民众'],
            'byte_length': 4,
            'byte_offset': 284,
            'formal': '',
            'item': '民众',
            'loc_details': [],
            'ne': '',
            'pos': 'n',
            'uri': ''},
           {'basic_words': ['激动'],
            'byte_length': 4,
            'byte_offset': 288,
            'formal': '',
            'item': '激动',
            'loc_details': [],
            'ne': '',
            'pos': 'a',
            'uri': ''},
           {'basic_words': ['跳跃'],
            'byte_length': 4,
            'byte_offset': 292,
            'formal': '',
            'item': '跳跃',
            'loc_details': [],
            'ne': '',
            'pos': 'vn',
            'uri': ''},
           {'basic_words': ['造成'],
            'byte_length': 4,
            'byte_offset': 296,
            'formal': '',
            'item': '造成',
            'loc_details': [],
            'ne': '',
            'pos': 'v',
            'uri': ''},
           {'basic_words': ['。'],
            'byte_length': 2,
            'byte_offset': 300,
            'formal': '',
            'item': '。',
            'loc_details': [],
            'ne': '',
            'pos': 'w',
            'uri': ''}],
 'log_id': 5196460719007475109,
 'text': '世界杯爆冷门,墨西哥球迷激动跳跃引发首都墨西哥城地震!墨西哥地震预警监控系统17日发布消息,当天墨西哥队在对阵德国队的世界杯比赛中,上半场比赛进行至第35分钟时,墨西哥队前锋洛萨诺打破僵局攻入首球,进球时墨西哥城监测到轻微地震。这一监控系统分析说,这次地震是由人为方式引发,或因进球时许多民众激动跳跃造成。'}

提取所需内容

NNP ={}
for eachWord in  result_dir['items']:
    if eachWord['ne']!="":
        word = eachWord["item"]
        nnP =  eachWord['ne']
        NNP[word] = nnP
缩略词 含义 缩略词 含义 缩略词 含义 缩略词 含义
PER 人名 LOC 地名 ORG 机构名 TIME 时间
for key in NNP.keys():
    print(key, ':', NNP[key])
第35分钟 : TIME
洛萨诺 : PER
德国队 : ORG
当天 : TIME
墨西哥城 : LOC
墨西哥队 : ORG
17日 : TIME
上半场 : TIME
墨西哥 : LOC

{
“text”:”百度是一家高科技公司”,
“items”:[
{
“byte_length”:4,
“byte_offset”:0,
“formal”:”“,
“item”:”百度”,
“ne”:”ORG”,
“pos”:”“,
“uri”:”“,
“loc_details”:[ ],
“basic_words”:[“百度”]
},
{
“byte_length”:2,
“byte_offset”:4,
“formal”:”“,
“item”:”是”,
“ne”:”“,
“pos”:”v”,
“uri”:”“,
“loc_details”:[ ],
“basic_words”:[“是”]
},
{
“byte_length”:4,
“byte_offset”:6,
“formal”:”“,
“item”:”一家”,
“ne”:”“,
“pos”:”m”,
“uri”:”“,
“loc_details”:[ ],
“basic_words”:[“一”,”家”]
},
{
“byte_length”:6,
“byte_offset”:10,
“formal”:”“,
“item”:”高科技”,
“ne”:”“,
“pos”:”n”,
“uri”:”“,
“loc_details”:[ ],
“basic_words”:[“高”,”科技”]
},
{
“byte_length”:4,
“byte_offset”:16,
“formal”:”“,
“item”:”公司”,
“ne”:”“,
“pos”:”n”,
“uri”:”“,
“loc_details”:[ ],
“basic_words”:[“公司”]
}
]
}

将代码集成一下

# -*- coding: utf-8 -*-
import urllib3
import json
import urllib.request 
def baiduNER(myData,APIurl,access_token):
    url = APIurl+access_token
    data ={"text":myData}
    encode_data= json.dumps(data).encode('GBK')
    http = urllib3.PoolManager()
    #JSON:在发起请求时,可以通过定义body 参数并定义headers的Content-Type参数来发送一个已经过编译的JSON数据:
    request = http.request('POST',
                           url,
                           body=encode_data,
                           headers={'Content-Type':'application/json'}
                           )
    result = str(request.data,"GBK")
    result_dir = eval(result)
    NNP ={}
    if "items" in  result_dir.keys():
        for eachWord in  result_dir.setdefault("items"):
            if eachWord['ne']!="":
                word = eachWord.get("item")
                nnP =  eachWord['ne']
                NNP[word] = nnP
    return NNP
lawText="""
省略处理上海市闵行区人民法院
刑 事 判 决 书
(2016)沪0112刑初2598号
公诉机关上海市闵行区人民检察院。
被告人许洪芳,女,1957年9月10日出生,汉族,户籍地上海市闵行区。
辩护人李霄,上海嘉钰律师事务所律师。
被告人自报张同平,男,1968年7月1日出生,汉族,户籍地安徽省铜陵市。.....当及时返还;违禁品和供犯罪所用的本人财物,应当予以没收。没收的财物和罚金,一律上缴国库,不得挪用和自行处理。
"""
def main():
    #百度AI开放平台通行证
    access_token ="24.340837cdde292a61442507b60e6fb64c.2592000.1532060546.282335-11012308"
    ##具体接口的链接
    APIurl = "https://aip.baidubce.com/rpc/2.0/nlp/v1/lexer?access_token="
    # # myData = ' '.join(each for each in lawText.split())
    # NNP = baiduNER(myData,APIurl,access_token)  短文本这样
    myDataAll =lawText.split("\n")
    NNP ={}
    for each in myDataAll:
      NNPnew =baiduNER(each,APIurl,access_token)
      NNP.update(NNPnew)
    for key in NNP.keys():
        print(key, ':', NNP[key]) 
if __name__ == '__main__':
    main()   

结果部分为:

上海陈行炼油厂 : ORG
最高人民检察院 : ORG
2016330日上午 : TIME
当天 : TIME
胡某某 : PER
李霄 : PER
丁志 : TIME
汉族 : ORG
2016331日 : TIME
2016615日起 : TIME
李某 : PER
中储 : ORG
2015621日 : TIME
三十日内 : TIME
浦江镇 : LOC
315日 : TIME
五年 : TIME
616日 : TIME
丁某 : PER

猜你喜欢

转载自blog.csdn.net/shuihupo/article/details/81541334