python如何识别字符串中的⼈名,如何识别⼀串拼⾳字符串以及韵母的提取
# python 如何识别字符串中的⼈名,如何识别⼀串拼⾳字符串以及韵母的提取
## ⼀、识别字符串中的⼈名或特定名词
### 1.安装Python SDK
~~~markdown
安装⽅法:pip install baidu-aip
~~~
### 2.获取APP ID
~~~markdown
为了使⽤这个接⼝,我们还需要获取到百度智能云提供的账号(如下图中的APPID、  API KEY、  SECRET KEY)。
登录官⽹后,我们需要在百度智能云的管理中⼼创建⼀个应⽤,这样我们就能通过这个ID使⽤接⼝了,如下图。⽹址
console.bce.baidu/ai/#/ai/nlp/overview/index
~~~
![20191024184444895](assets/20191024184444895.png)
### 3.代码调⽤
~~~python
def get_chinese_name(text):
"""
:param text: 中⽂字符串
:return: ⼈名
"""
"""识别⼈名"""
# 上⼀步获取到的ID AK SK
APP_ID = '你的ID'
API_KEY = '你的AK'
SECRET_KEY = '你的SK'
client = AipNlp(APP_ID, API_KEY, SECRET_KEY)python正则表达式判断
text = de('gbk', 'ignore'), encoding='gbk')  # ignore忽略⽆法编码的字符,如果不加这个会报错。
# 设置请求间隔,免费版的QPS限制为2,有能⼒的可以购买。
time.sleep(1)
# 调⽤词法分析的返回结果
print(client.lexer(text))
""" 调⽤词法分析 """
for i in client.lexer(text)['items']:
# 若字符串中有⼈名就返回⼈名
if i['ne'] == 'PER':
return i['item']
return''
~~~
我们测试⼀段字符串
~~~python
text = "这是⼀段测试⽂本,我的中⽂名是媛媛"
print(get_chinese_name(text))
~
~~
返回结果
~~~python
{'log_id': 375282685928253176, 'text': '这是⼀段测试⽂本,我的中⽂名是媛媛', 'items': [{'loc_details': [], 'byte_offset': 0, 'uri': '', 'pos': 'r', 'ne': '', 'item': '这', 'basic_words': ['这'], 'byte_length': 2, 'formal': ''}, {'loc_details': [], 'byte_offset': 2, 'uri 媛媛
~~~
### 4.参数说明
~~~markdown
在这⾥还需要说明⼀下接⼝返回参数。为了⽅便,我们先把上⼀步得到的数据格式化如下,其中
pos : 词性,词性标注算法使⽤。
~~~
####  **词性缩略说明**
***ne :*** 命名实体类型。如下⾯例⼦中的“媛媛”的ne关键字为PER ,表⽰⼈名。
![词性缩略说明](assets/词性缩略说明.png)
####  **专名识别缩略词含义**
![专名识别缩略词含义](assets/专名识别缩略词含义.png)
~~~python
{
'log_id': 375282685928253176,
'text': '这是⼀段测试⽂本,我的中⽂名是媛媛',
'items': [{
'loc_details': [],
'byte_offset': 0,
'uri': '',
'pos': 'r',
'ne': '',
'item': '这',
'basic_words': ['这'],
'byte_length': 2,
'formal': ''
}, {
'loc_details': [],
'byte_offset': 2,
'uri': '',
'pos': 'v',
'ne': '',
'item': '是',
'basic_words': ['是'],
'byte_length': 2,
'formal': ''
}, {
'loc_details': [],
'byte_offset': 4,
'uri': '',
'pos': 'm',
'ne': '',
'item': '⼀段',
'basic_words': ['⼀', '段'],
'byte_length': 4,
'formal': ''
}, {
'loc_details': [],
'byte_offset': 8,
'uri': '',
'pos': 'vn',
'ne': '',
'item': '测试',
'basic_words': ['测试'],
'byte_length': 4,
'formal': ''
}, {
'loc_details': [],
'byte_offset': 12,
'uri': '',
'pos': 'n',
'ne': '',
'item': '⽂本',
'basic_words': ['⽂本'],
'byte_length': 4,
'formal': ''
}, {
'loc_details': [],
'byte_offset': 16,
'uri': '',
'pos': 'w',
'ne': '',
'item': ',',
'basic_words': [','],
'byte_length': 1,
'formal': ''
}, {
'loc_details': [],
'byte_offset': 17,
'uri': '',
'pos': 'r',
'ne': '',
'item': '我',
'basic_words': ['我'],
'byte_length': 2,
'formal': ''
}, {
'loc_details': [],
'byte_offset': 19,
'uri': '',
'pos': 'u',
'ne': '',
'item': '的',
'basic_words': ['的'],
'byte_length': 2,
'formal': ''
}, {
'loc_details': [],
'byte_offset': 21,
'uri': '',
'pos': 'n',
'ne': '',
'item': '中⽂名',
'basic_words': ['中⽂', '名'],
'byte_length': 6,
'formal': ''
}, {
'loc_details': [],
'byte_offset': 27,
'uri': '',
'pos': 'v',
'ne': '',
'item': '是',
'basic_words': ['是'],
'byte_length': 2,
'formal': ''
}, {
'loc_details': [],
'byte_offset': 29,
'uri': '',
'pos': '',
'ne': 'PER',
'item': '媛媛',
'basic_words': ['媛媛'],
'byte_length': 4,
'formal': ''
}]
}
~
~~
## ⼆、把⼀串拼⾳字符串分割成独⽴的拼⾳
~~~markdown
假如我们要将字符串 “zhoujielun” 分割成 “zhou-jie-lun”这样的格式,那么我们可以采取逆向匹配的⽅法,即下图中字符串的指针A向B移动过程中不断匹配拼⾳表(拼⾳表可⾃⾏下载),直到字符串s[A:]在拼⾳表中,就匹配成功。重复这⼀过程就可~~~
![20191025125215453](assets/20191025125215453.png)
算法直接看代码
~~~python
def pinyin_word(string):
'''
将⼀段拼⾳,分解成⼀个个拼⾳
:param string: 匹配的字符串
:return: 匹配到的拼⾳列表
'''
max_len = 6  # 拼⾳最长为6
string = string.lower()
stringlen = len(string)
result = []
# 读本地拼⾳表
with open('', 'r', encoding='utf-8') as fi:
pinyinLib = fi.readlines()
for i in range(len(pinyinLib)):
pinyinLib[i] = pinyinLib[i][:-1]  # 去换⾏符
# 逆向匹配
while True:
matched = 0
matched_word = ''
if stringlen < max_len:
max_len = stringlen
for i in range(max_len, 0, -1):
s = string[(stringlen-i):stringlen]
# 字符串是否在拼⾳表中
if s in pinyinLib:
matched_word = s
matched = i
break
# 未匹配到拼⾳
if len(matched_word) == 0:
break
else:
result.append(s)
string = string[:(stringlen-matched)]
stringlen = len(string)
if stringlen == 0:
break
return result
print(pinyin_or_word('zhoujielun'))
输出结果:['lun', 'jie', 'zhou']
~~~
## 三、拼⾳韵母的提取
做法和上⼀点相同,建⽴⼀个韵母表,逆向匹配即可。
~~~python
def pinyin_word(string):
'''
将⼀段拼⾳,分解成⼀个个拼⾳
:
param string: 匹配的字符串
:return: 匹配到的拼⾳列表
'''
max_len = 6  # 拼⾳最长为6
string = string.lower()
stringlen = len(string)
result = []
# 读本地拼⾳表
with open('', 'r', encoding='utf-8') as fi:
pinyinLib = fi.readlines()
for i in range(len(pinyinLib)):
pinyinLib[i] = pinyinLib[i][:-1]  # 去换⾏符
# 逆向匹配
while True:
matched = 0
matched_word = ''
if stringlen < max_len:
max_len = stringlen
for i in range(max_len, 0, -1):
s = string[(stringlen-i):stringlen]
# 字符串是否在拼⾳表中
if s in pinyinLib:
matched_word = s
matched = i
break
# 未匹配到拼⾳
if len(matched_word) == 0:
break
else:
result.append(s)
string = string[:(stringlen-matched)]
stringlen = len(string)
if stringlen == 0:
break
return result
~~~
## 四、⼀些⽅法整理
### 1.读xlsx格式
~~~python
import xlrd
data = xlrd.open_workbook('data.xlsx')
table = data.sheet_by_index(0)  # 按索引
nrows = ws
ncol = ls
rowvalue = w_values(0)    # 第0⾏数据
colvalue = l_values(0)    # 第0列数据
print(rowvalue, colvalue)
~~~
### 2.判断中⽂字符串
~~~python
import re
Pattern = repile(u'[\u4e00-\u9fa5]+')  # 判断是否是中⽂的正则表达式对象    match = Pattern.match(string)
# 判断字符串是否为汉字
if match:
zh_name = up()
print(zh_name)
~~~
### 3.汉字转拼⾳
~~~python
不带语调的汉字转拼⾳:
from pypinyin import pinyin, lazy_pinyin
# 汉字转为拼⾳
new_name = '我爱编程'
new_name = ''.join(lazy_pinyin(new_name))
print(new_name)
输出结果:woaibiancheng
~
~~
获取APP ID
词性缩略说明
专名识别缩略词含义