0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Ruby から classify text API を叩く

Posted at

ゴール

以下を Ruby から叩く。

事前準備

上記 API は Natural Language API の一つなので、https://qiita.com/tommy-012/items/e0ad2a7c985fad5e59dd の準備ができてれば OK

API 仕様

↑には明記されていないが、Gme を使った際に分かったこととして、対象の英語文に最低限 20 個の単語が含まれている必要がある

カテゴリ一覧は、https://cloud.google.com/natural-language/docs/categories
現状は、最上位カテゴリは 27 個(結構多い)
また、より詳しいカテゴリがわかる場合は、それより上位のカテゴリは省略される

"/Adult"
"/Arts & Entertainment"
"/Autos & Vehicles"
"/Beauty & Fitness"
"/Books & Literature"
"/Business & Industrial"
"/Computers & Electronics"
"/Finance"
"/Food & Drink"
"/Games"
"/Health"
"/Hobbies & Leisure"
"/Home & Garden"
"/Internet & Telecom"
"/Jobs & Education"
"/Law & Government"
"/News"
"/Online Communities"
"/People & Society"
"/Pets & Animals"
"/Real Estate"
"/Reference"
"/Science"
"/Sensitive Subjects"
"/Shopping"
"/Sports"
"/Travel"

Gem から API を叩く

require 'google/apis/language_v1'

# Doc: https://googleapis.dev/ruby/google-api-client/v0.23.6/Google/Apis/LanguageV1/CloudNaturalLanguageService.html#classify_document_text-instance_method
service = Google::Apis::LanguageV1::CloudNaturalLanguageService.new
service.key = 'APIキー'

# Doc: https://googleapis.dev/ruby/google-api-client/v0.23.6/Google/Apis/LanguageV1/ClassifyTextRequest.html
request = Google::Apis::LanguageV1::ClassifyTextRequest.new({
  document: {
    type: 'PLAIN_TEXT',
    language: 'en',
    content: 'Nintendo's home video game console "Nintendo Switch" will be released simultaneously in Japan, North America, Europe, Australia, Hong Kong, etc.',
  }
})

# Doc: https://googleapis.dev/ruby/google-api-client/v0.23.6/Google/Apis/LanguageV1/ClassifyTextResponse.html
response = service.classify_document_text(request)

# Doc: https://googleapis.dev/ruby/google-api-client/v0.23.6/Google/Apis/LanguageV1/ClassificationCategory.html
response.categories
=> [#<Google::Apis::LanguageV1::ClassificationCategory:0x00007fbdf9214ee0 @confidence=0.77, @name="/Games/Computer & Video Games">, #<Google::Apis::LanguageV1::ClassificationCategory:0x00007fbdf4b038d0 @confidence=0.66, @name="/Computers & Electronics/Consumer Electronics">]

response.categories.first.name
=> "/Games/Computer & Video Games"

response.categories.second.name
=> "/Computers & Electronics/Consumer Electronics"
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?