遭遇したver
google-cloud-translate (3.2.3)
google-cloud-translate-v2 (0.3.1)
google-cloud-translate-v3 (0.4.2)
現象
text = "お腹空いた"
response = Google::Cloud::Translate.translation_service.translate_text(
contents: [text],
target_language_code: "en",
parent: YOUR_GOOGLE_CLOUD_PROJECT_ID
)
translate_result = response.translations.first
puts translate_result.translated_text
#=> "I'm hungry"
解決法1: 返ってきたものをunescapeする
text = "お腹空いた"
response = Google::Cloud::Translate.translation_service.translate_text(
contents: [text],
target_language_code: "en",
parent: YOUR_GOOGLE_CLOUD_PROJECT_ID
)
translate_result = response.translations.first
puts CGI.unescapeHTML(translate_result.translated_text)
#=> "I'm hungry"
解決法2: mime_typeにtext/plainを指定してAPIを使う
ここのIssueのやりとりで見つけました。
https://github.com/googleapis/google-cloud-ruby/issues/4775
text = "お腹空いた"
response = Google::Cloud::Translate.translation_service.translate_text(
contents: [text],
target_language_code: "en",
parent: YOUR_GOOGLE_CLOUD_PROJECT_ID,
mime_type: 'text/plain' # これを追加
)
translate_result = response.translations.first
puts translate_result.translated_text
#=> "I'm hungry"