我還與一些這方面的問題,並寫了一個小功能,從API獲取數據:
#' Translate with R
#'
#' Translate Keywords or/and text with the Google Translate API
#' The Functions allows to translate keywords or sentences using the Google Translate API.
#' To use this function you need to get a API-Key for the Google Translate API <https://cloud.google.com/translate/docs/?hl=en>.
#' @param text The keyword/sentence/text you want to translate
#' @param API_Key Your API Key. You get the API Key here: <https://cloud.google.com/translate/docs/?hl=en>
#' @param target The Language target your text translated to. For German 'de'.
#' @param source The Language your given text/keyword is. For example 'en' - english
#' translate()
#' @examples
#' \dontrun{
#' translate(text = "R is cool", API_Key = "XXXXXXXXXXX", target = "de", source = "en")
#' }
translate <- function(text,
API_Key,
target = "de",
source = "en") {
b <- paste0(
'{
"q": [
"',
text,
'"
],
"target": "',
target,
'",
"source": "',
source,
'",
"format": "text"
}'
)
url <-
paste0("https://translation.googleapis.com/language/translate/v2?key=",
API_Key)
x <- httr::POST(url, body = b)
x <- jsonlite::fromJSON(rawToChar(x$content))
x <- x$data$translations
return(x$translatedText[1])
}
更新要點在這裏:https://gist.github.com/dschmeh/8414b63c3ab816c44995cd6872165f0e
服務器和瀏覽器的API不會幫你,你需要Google的翻譯API。 https://cloud.google.com/translate/docs/ –
對不起,您能澄清一下嗎?我已經啓用了谷歌的翻譯API - 這是我最初獲得'服務器'和'瀏覽器'API密鑰的方式。 R包'translate'和'translateR'應該是我對這些密鑰的理解。我錯過了什麼? –
您的API請求是否需要在文件上擁有包含結算信息的Google帳戶?如果沒有,那麼你得到了錯誤的API。 –