微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用Google Cloud Translate v3翻译长文本

如何解决如何使用Google Cloud Translate v3翻译长文本

环境: 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。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。