みんなの自動翻訳@TexTraのWebAPIをRから使用する
目的
みんなの自動翻訳@TexTra® の質問・要望欄を見ていたら、Web APIのRでのアクセス例の追加要望があったのでスクレイピングの練習も兼ねてやってみた。
コード
汚いコードですが動くのでOKです。
余力があったらパッケージ化してGitHubに上げる上げた。 (GitHub - fmsan51/minhon)
if (!require("pacman")) install.packages("pacman"); library(pacman) pacman::p_load(httr, rvest) # ユーザーID login_id <- "User ID here" # https://mt-auto-minhon-mlt.ucri.jgn-x.jp/content/mt/ から適当なものを選択 # 以下の例は英→日 api_key <- "API key here" api_secret <- "API secret here" base_url <- "https://mt-auto-minhon-mlt.ucri.jgn-x.jp" api_name <- "mt" api_param <- "generalNT_en_ja" # 翻訳対象テキスト text <- "The quick brown fox jumps over the lazy dog" endpoint <- oauth_endpoint(NULL, NULL, paste0(base_url, "/oauth2/token.php")) app <- oauth_app("minhon", api_key, api_secret) token <- oauth2.0_token(endpoint, app, client_credentials = T) res <- POST(paste0(base_url, "/api/"), body = list(access_token = token$credentials$access_token, key = api_key, api_name = api_name, api_param = api_param, name = login_id, type = "xml", # jsonも可 text = text)) res_text <- html_element(content(res, encoding = "UTF-8"), xpath = "/resultset/result/information/text-t") html_text(res_text)