java 如何使用java代码将一种语言翻译成另一种语言

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33706132/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 22:01:44  来源:igfitidea点击:

How to translate one language to another using java code

javagoogle-translate

提问by Venkatesh Bodapati

import java.util.ArrayList;

import com.google.api.translate.Language;
import com.google.api.translate.Translator;

public class Translation {
    public static void main(String[] args) {                
        // Translate a single English String to French
        Translator translator = new Translator();
        System.out.println("Saying goodbye in French:");
        System.out.println(translator.translate("goodbye", Language.ENGLISH, Language.FRENCH));

        System.out.println();
    }
}

回答by Yong Liu

First, Google translate API is a paid service: https://cloud.google.com/pricing/

首先,谷歌翻译API是付费服务:https: //cloud.google.com/pricing/

Second, you have to create your own API key and use the key in your app: https://console.developers.google.com.

其次,您必须创建自己的 API 密钥并在您的应用程序中使用该密钥:https: //console.developers.google.com

The code I am using:

我正在使用的代码:

HttpTransport httpTransport = AndroidHttp.newCompatibleTransport();
AndroidJsonFactory jsonFactory = AndroidJsonFactory.getDefaultInstance();
Translate.Builder builder = new Translate.Builder(httpTransport, jsonFactory, null);
// need this, otherwise you get warning
builder.setApplicationName("Give a name");
Translate translate = builder.build();
List<String> list = new ArrayList<String>();
// I only add one char to the list
list.add(String.valueOf(word[0]));
Translate.Translations.List request = translate.translations().list(list, "en").setKey("<your_api_key>");
String result = request.execute().getTranslations().get(0).getTranslatedText();

Note: don't know the reason yet, I always got the same error if I use my android API key: "com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden", and the reason says "ipRefererBlocked", but it is fine if I use my Browser Key. Hope someone else can figure out the reason.

注意:还不知道原因,如果我使用我的 android API 密钥,我总是遇到同样的错误:“com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden”,原因是“ipRefererBlocked” ,但如果我使用我的浏览器密钥就可以了。希望其他人能找出原因。