问题描述
环境: API:Google Cloud Translate V3, 文字大小:12 000字
可以通过translateText()
方法翻译单词和简短的句子,但是当我运行整个文本时,遇到了“文本太长”错误。
"message": "Text is too long.","code": 3,"status": "INVALID_ARGUMENT","details": [
{
"@type": 0,"data": "type.googleapis.com\/google.rpc.BadRequest"
},{
"@type": 0,"data": [
{
"field": "contents","description": "The total codepoints in the request must be less than 30720,actual: 90005"
}
]
}
]
}
解决方法
U 可以将文本分成多个部分(多个请求),在 contents[]
内最多有 30k 个代码点,如 API 中所述:https://cloud.google.com/translate/docs/reference/rest/v3/projects.locations/translateText
// Request 1
{
"sourceLanguageCode": "en","targetLanguageCode": "de","contents": ["Text part one..."]
}
// Request 2
{
"sourceLanguageCode": "en","contents": ["...text part two..."]
}
// Request n
{
"sourceLanguageCode": "en","contents": ["...text part n."]
}
或者使用批量翻译,以异步批量模式翻译大量文本:https://cloud.google.com/translate/docs/reference/rest/v3/projects.locations/batchTranslateText。这个有点复杂,因为您必须将文件上传到 Google Cloud Storage。