百度AI 開放平臺API調用

近來要了解自然語言處理方面的技術,拿百度API做個實驗對,進行多次編碼嘗試最終成功調用。

在本人博客百度API使用系列,使用python代碼實現。涉及內容如下:

1.    (一)百度AI 開放平臺API調用之AccessToken獲取

2.    (二)百度AI 開放平臺API調用之應用實踐

  •   代碼修改中出現的錯誤,及最終的方法  
  •  錯誤提示:"error_code": 282004,error_msg":"invalidparameter(s)"

    ·            not a valid non-string sequence or mapping object

(一)百度AI 開放平臺API調用之AccessToken獲取

本節是AccessToken的獲取,編寫原因是因爲百度官方說明是針對python2的代碼,使用urllib2在python已經棄用,且給出的獲取代碼還是需要加工才能保證整個調用流程的連貫性。現把使用過程進行分享。

實驗使用的環境是Windows10  Python3

首相查看官方說明文檔

獲取Access Token

請求URL數據格式

向授權服務地址https://aip.baidubce.com/oauth/2.0/token發送請求(推薦使用POST),並在URL中帶上以下參數:

·        grant_type 必須參數,固定爲client_credentials

·        client_id 必須參數,應用的APIKey

·        client_secret 必須參數,應用的SecretKey

例如:

https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=Va5yQRHlA4Fq5eR3LT0vuXV4&client_secret=0rDSjzQ20XUj5itV6WRtznPQSzr5pVw2&

形象化即:

https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=【官網獲取的AK&client_secret=【官網獲取的SK

參數是個人創建應用的參數或者自己應用的匹配密鑰。

獲取AccessToken代碼:

代碼的優勢不僅在於得到access_token,更在於將其存爲變量,方便隨後的直接使用。

#!/ Mypython
# -*- coding: utf-8 -*-
# @Time    : 2018/4/4 18:36
# @Author  : LinYimeng
# @File    : test1.py
# @Software: PyCharm
import urllib
###第一步:獲取access_token
# client_id 爲官網獲取的AK, client_secret 爲官網獲取的SK,以下一行按自己實際填寫
host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=****grant_type&client_id=****&client_secret=****'
request = urllib.request.Request(host)
request.add_header('Content-Type', 'application/json; charset=UTF-8')
response = urllib.request.urlopen(request)
content = response.read()
if (content):
    print(type(content))#<class 'bytes'>
content_str=str(content, encoding="utf-8")
###eval將字符串轉換成字典
content_dir = eval(content_str)
access_token = content_dir['access_token']

若請求錯誤,服務器將返回的JSON文本包含以下參數:

·        error 錯誤碼;關於錯誤碼的詳細信息請參考下方鑑權認證錯誤碼。

·        error_description 錯誤描述信息,幫助理解和解決發生的錯誤。

鑑權認證錯誤碼

error

error_description

解釋

invalid_client

unknown client id

API Key不正確

invalid_client

Client authentication failed

Secret Key不正確

歡迎分享和轉載,請註明出處 shuihupohttps://blog.csdn.net/shuihupo/article/details/79862004點擊打開鏈接

實驗使用的環境是Windows10  Python3

(二)百度AI 開放平臺API調用之應用實踐

歡迎分享和轉載,請註明出處

 shuihupohttps://blog.csdn.net/shuihupo/article/details/79862004


實驗使用的環境是Windows10  Python3

選擇調用的接口,eg:

詞法分析接口

仔細閱讀官方接口說明

·        接口描述

·        請求說明

·         

·        HTTP方法POST

·        (通用版)請求URL: https://aip.baidubce.com/rpc/2.0/nlp/v1/lexer

·        (定製版)請求URL: https://aip.baidubce.com/rpc/2.0/nlp/v1/lexer_custom

·        URL參數:

參數

access_token

通過API KeySecret Key獲取的access_token,參考Access Token獲取

·        Header如下:

參數

Content-Type

application/json

·        body請求示例:

·       {

·         "text": "百度是一家高科技公司"

·       }

請求參數

參數名稱

類型

詳細說明

text

string

待分析文本(目前僅支持GBK編碼),長度不超過20000字節

POST方式調用

注意:要求使用JSON格式的結構體來描述一個請求的具體內容。**發送時默認需要對body整體進行GBK編碼**若使用UTF-8編碼,請在url參數中添加charset=UTF-8 (大小寫敏感)例如:https://aip.baidubce.com/rpc/2.0/nlp/v1/lexer?charset=UTF-8&access_token=24.f9ba9c5241b67688bb4adbed8bc91dec.2592000.1485570332.282335-8574074

返回格式

JSON格式,返回內容爲GBK編碼

這些注意事項提醒我們要注意編碼的問題。

法一:使用使用urllib時會返回如下錯誤,搜索解決方法是因爲傳入數據是字典需要編碼。
post_data=json.dumps(post_data).encode('GBK')

282004

invalid parameter(s)

請求中包含非法參數,請檢查後重新嘗試

也不說怎麼錯了,上正確的代碼吧。

#!/ Mypython
# -*- coding: utf-8 -*-
# @Time    : 2018/3/28 16:48
# @Author  : LinYimeng
# @File    : baidulearn.py
# @Software: PyCharm
import urllib
import urllib3
import json
 ###第一步:獲取access_token
# client_id 爲官網獲取的AK, client_secret 爲官網獲取的SK
host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=pd152AVsnYc6Nbfk5Yuh9XTh&client_secret=ZTn7ASCKAGgPFEFmMxszEoQmAlVb2LRM'
request = urllib.request.Request(host)
request.add_header('Content-Type', 'application/json; charset=UTF-8')
response = urllib.request.urlopen(request)
content = response.read()
if (content):
    print(type(content))#<class 'bytes'>
content_str=str(content, encoding="utf-8")
###
content_dir = eval(content_str)
access_token = content_dir['access_token']
####第二部分調用
###api地址
import sys
print(sys.getdefaultencoding())
http=urllib3.PoolManager()
url = "https://aip.baidubce.com/rpc/2.0/nlp/v1/lexer?access_token="+access_token
data = {"text":"昆明會下雨嗎?"}
encodedata=json.dumps(data).encode('GBK')
request = urllib.request.Request(url, encode_data)
request.add_header('Content-Type', 'application/json')
response = urllib.request.urlopen(request)
content = response.read()  # content是一個utf-8格式的<class 'bytes'>
#bytes ⇒ str:str(b, encoding='utf-8')
content_str = str(content, encoding="gbk")
#  content被編碼爲gbk格式的字節串,賦給content_str
print(type(content_str))
if (content_str):
    print(content_str)

法二:使用使用urllib3
#!/ Mypython
# -*- coding: utf-8 -*-
# @Time    : 2018/3/28 16:48
# @Author  : LinYimeng
# @File    : baidulearn.py
# @Software: PyCharm

import urllib
import urllib3
import json

 ###第一步:獲取access_token
# client_id 爲官網獲取的AK, client_secret 爲官網獲取的SK
host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=pd152AVsnYc6Nbfk5Yuh9XTh&client_secret=ZTn7ASCKAGgPFEFmMxszEoQmAlVb2LRM'
request = urllib.request.Request(host)
request.add_header('Content-Type', 'application/json; charset=UTF-8')
response = urllib.request.urlopen(request)
content = response.read()
if (content):
    print(type(content))#<class 'bytes'>
content_str=str(content, encoding="utf-8")
###
content_dir = eval(content_str)
access_token = content_dir['access_token']
####第二部分調用
###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":"昆明會下雨嗎"}
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')
print(result)


結果:{"log_id":7265183527788840706, "text": "今天北京天氣怎麼樣?","items": [{"loc_details": [], "byte_offset": 0,"uri": "", "pos": "", "ne":"TIME", "item": "今天","basic_words": ["今天"],"byte_length": 4, "formal": ""},{"loc_details": [], "byte_offset": 4, "uri":"", "pos": "", "ne": "LOC","item": "北京","basic_words": ["北京"],"byte_length": 4, "formal": ""},{"loc_details": [], "byte_offset": 8, "uri":"", "pos": "n", "ne": "","item": "天氣","basic_words": ["天氣"],"byte_length": 4, "formal": ""},{"loc_details": [], "byte_offset": 12, "uri":"", "pos": "r", "ne": "","item": "怎麼樣","basic_words": ["怎麼", "樣"], "byte_length": 6,"formal": ""}, {"loc_details": [],"byte_offset": 18, "uri": "", "pos":"w", "ne": "", "item": "?", "basic_words": ["?"], "byte_length": 2,"formal": ""}]}

在實體命名方面,可以是識別到“昆明”是地名等信息。

 18年6月20:摸索的新的代碼,更清晰的顯示

# -*- coding: utf-8 -*-
import urllib
import urllib3
import json
import urllib.request
# with open(filename, 'r', encoding='utf8') as sampleFile:
#     lawText = sampleFile.read()
lawText="""昆明,雲南省轄下地級市,地處雲貴高原中部,北與涼山彝族自治州相連,西南與玉溪市、東南與紅河哈尼族彝族自治州毗鄰,西與楚雄彝族自治州接壤,東與曲靖市交界,是滇中城市羣的核心圈、亞洲5小時航空圈的中心,國家一級物流園區佈局城市之一。
"""
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
def main():
    #百度AI開放平臺通行證
    access_token ="2#####你的"
    ##具體接口的鏈接
    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()

("PER	人名	LOC	地名	ORG	機構名	TIME	時間")
結果爲:

玉溪市 : LOC

紅河哈尼族彝族自治州 : LOC
雲南省 : LOC
亞洲 : LOC
雲貴高原 : LOC
西南 : LOC
楚雄彝族自治州 : LOC
曲靖市 : LOC
5小時 : TIME
一級物流園區 : LOC
涼山彝族自治州 : LOC
滇中城市羣 : LOC
昆明 : LOC

歡迎分享和轉載,請註明出處在雲南省高校數據化運營管理工程研究中心https://blog.csdn.net/m0_37788308/article/details/79994499點擊打開鏈接

博客同時本博客文章同步在shuihupo:https://blog.csdn.net/shuihupo/article/details/79862004點擊打開鏈接


發佈了53 篇原創文章 · 獲贊 124 · 訪問量 23萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章