ruby meaning_cloud.rb

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby meaning_cloud.rb相关的知识,希望对你有一定的参考价值。

require_relative 'meaning_cloud'

MeaningCloud.api_key =  ENV['MC_KEY']

MeaningCloud.sentiment(txt: 'I would like to see if the sentiments extracted are happy or sad.')
require 'faraday'
require 'dotenv'
require 'json'

module MeaningCloud
  def self.topics(options)
    request :topics, options, lang: 'en', tt: 'ecr'
  end

  def self.sentiment(options)
    request :sentiment, options, model: 'auto'
  end

  def self.text_classification(options)
    request :class, options, model: 'IPTC_en'
  end

  def self.lang(options)
    request :lang, options
  end

  class << self
    attr_accessor :api_key

    def request(what, arguments, defaults={})
      payload = {
        key: api_key,
        of: :json
      }.merge(defaults).merge(arguments)

      version = current_version_for(what)

      response = Response.new JSON.parse api.post("#{what}-#{version}", payload).body
    end

    def api
      @api ||= Faraday.new 'https://api.meaningcloud.com'
    end

    def current_version_for(what)
      {
          topics: '1.2',
          sentiment: '2.0',
          class: '1.1',
          lang: '1.1'
      }[what] || '2.0'
    end
  end

  private_class_method :request, :api, :current_version_for

  class Response
    attr_reader :status, :message, :body, :credits, :remaining_credits

    def initialize(json)
      status = json.delete 'status'

      @status = status['code']
      @message = status['msg']
      @body = json
      @credits, @remaining_credits = status['credits'].to_i, status['remaining_credits'].to_i

      raise ApiError, message unless success?
    end

    def success?
      status === '0'
    end
  end

  class ApiError < Exception
  end
end

以上是关于ruby meaning_cloud.rb的主要内容,如果未能解决你的问题,请参考以下文章

Ruby运算符

Ruby 25 岁了!Ruby 之父说 Ruby 3 有望 3 倍提速

如何学习ruby?Ruby学习技巧分享

ruby Ruby脚本,看看是否用openssl编译了ruby

什么是ruby?

ruby和ruby ee