ruby百度自然语言之文章标签接口

首先获取access_token

更其他接口一样,获取token需要2个参数, appid、appsecret,需要先添加应用

http://ai.baidu.com/docs#/Auth/top

def get_access_token
      now = Time.now
      now = now.to_i
      client = HttpClient.new(@access_token_url, @timeout, @skip_verify_ssl)

      data = client.get_json('baidu_access_token.json')
      expire_seconds = data.blank? ? '' : data['expire']
      access_token = nil


      # 过期时间为空或小于记录的时间
      if expire_seconds.blank? || expire_seconds < now
        get_info = client.post('token', '', params: { grant_type: 'client_credentials', client_id: @client_id , client_secret: @client_secret })
        unless get_info['access_token'].nil?
          access_token = get_info['access_token']
          expire_seconds = now + 2592000
          data = {
            access_token: access_token,
            refresh_token: get_info['refresh_token'],
            scope: get_info['scope'],
            session_key: get_info['session_key'],
            session_secret: get_info['session_secret'],
            expire: expire_seconds
          }
          data_json = JSON.generate(data)
          client.set_json('baidu_access_token.json', data_json)
        end
      else
        access_token = data['access_token']
      end

      access_token
    end

获取标签接口

http://ai.baidu.com/docs#/NLP-API/a1dae901

url需要参数access_token, 同时需要传递2个参数,title、content, 目前只支持gbk,我使用的是utf8,所以需要转码

参数类型描述是否必填
titlestring文章标题(GBK编码),最大80字节必填
contentstring文章内容(GBK编码),最大65535字节必填

def get_tag(title, content)
      access_token = get_access_token
      client = HttpClient.new(@tag_url, @timeout, @skip_verify_ssl)
      tag_params = {
        'title' => title,
        'content' => content
      }
      tag_json = JSON.generate(tag_params)
      tag_json = tag_json.encode('GBK','utf-8',{:invalid => :replace, :undef => :replace, :replace => '?'})
      get_info = client.post('keyword', tag_json, params: { access_token: access_token })
      res = Array.new
      unless get_info['items'].blank?
        res = get_info['items']
      end
      res
    end

同样的,获取到的结果也需要转码


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值