Language Translation in Java Example
Java Code Examples for com.google.api.translate.Language
The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.
Example 1
From project BabelCraft-Legacy, under directory /src/main/java/com/craftfire/babelcraft/util/managers/.
Source file: TranslationManager.java
28
public boolean isLanguageSupported(String lang){ Language thelang=Language.fromString(lang); if (thelang != null) { return true; } return false; }
Example 2
From project Jetwick, under directory /src/main/java/de/jetwick/ui/.
Source file: ResultsPanel.java
27
public void fillTranslateMap(Collection<JTweet> tweets,String toLang){ Map<Integer,Long> index2Id=new LinkedHashMap<Integer,Long>(); String[] texts=new String[tweets.size()]; Language[] froms=new Language[tweets.size()]; Language[] tos=new Language[tweets.size()]; try { Language toLanguage=Language.fromString(toLang); Iterator<JTweet> iter=tweets.iterator(); for (int i=0; i < texts.length; i++) { JTweet tweet=iter.next(); index2Id.put(i,tweet.getTwitterId()); texts[i]=tweet.getText(); froms[i]=Language.AUTO_DETECT; tos[i]=toLanguage; } String newTxts[]=Helper.translateAll(texts,froms,tos); for (int i=0; i < newTxts.length; i++) { Long twitterId=index2Id.get(i); if (twitterId != null) translateMap.put(twitterId,newTxts[i]); } } catch ( Exception ex) { logger.error("Couldn't translate all tweets",ex); } }
Example 3
From project BabelCraft-Legacy, under directory /src/main/java/com/craftfire/babelcraft/.
Source file: BabelCraftManager.java
26
public String translate(String message,Player player){ Language lang; if (Config.language_serverforced) { lang=Language.fromString(Config.language_default); } else { lang=Managers.player.getLanguage(player); } return Managers.translation.translate(message,Language.AUTO_DETECT,lang); }
Example 4
From project multi-translator, under directory /src/com/robtheis/translator/.
Source file: TranslatorGoogle.java
25
/** * Check if the supplied language pair is valid for this translation service, and start an AsyncTask to request the translation. * @param text The text to translate * @param source The source language for translation * @param target The target language for translation * @param textView The text field that will receive the completed translation */ static void translate(String text,String source,String target,TextView textView){ if (source == null || target == null) { throw new IllegalArgumentException(); } Language sourceLanguage=null; Language targetLanguage=null; try { sourceLanguage=toLanguage(source); targetLanguage=toLanguage(target); } catch ( IllegalArgumentException e) { textView.setTypeface(Typeface.defaultFromStyle(Typeface.ITALIC),Typeface.ITALIC); textView.setTextSize(14); textView.setText("Unsupported language pair"); } if (sourceLanguage != null && targetLanguage != null) { if (text.length() > 4500) { text=text.substring(0,4500); } new TranslateGoogleAsyncTask(text,sourceLanguage,targetLanguage,textView).execute(); } else { textView.setTypeface(Typeface.defaultFromStyle(Typeface.ITALIC),Typeface.ITALIC); textView.setTextSize(14); textView.setText("Unsupported language pair"); } }
Example 5
From project Jetwick, under directory /src/main/java/de/jetwick/ui/.
Source file: OneTweet.java
24
public String translate(JTweet tweet){ String trText=getTextFromTranslateAllAction(tweet.getTwitterId()); if (trText != null) return trText; trText=tweet.getText(); if (clickedTranslate) { try { trText=Helper.translate(trText,Language.AUTO_DETECT,Language.fromString(language)); } catch ( Exception ex) { logger.error("cannot translate tweet:" + tweet + " "+ ex.getMessage()); } } return trText; }
Example 6
From project android-ocr, under directory /android/src/edu/sfsu/cs/orange/ocr/language/.
Source file: TranslatorGoogle.java
23
static String translate(String sourceLanguageCode,String targetLanguageCode,String sourceText){ Log.d(TAG,sourceLanguageCode + " -> " + targetLanguageCode); if (sourceText.length() > 4500) { sourceText=sourceText.substring(0,4500); } GoogleAPI.setKey(API_KEY); GoogleAPI.setHttpReferrer("https://github.com/rmtheis/android-ocr"); try { return Translate.DEFAULT.execute(sourceText,Language.fromString(sourceLanguageCode),Language.fromString(targetLanguageCode)); } catch ( Exception e) { Log.e(TAG,"Caught exeption in translation request."); return Translator.BAD_TRANSLATION_MSG; } }
Example 7
From project android-ocr, under directory /android/src/edu/sfsu/cs/orange/ocr/language/.
Source file: TranslatorGoogle.java
23
/** * Convert the given name of a natural language into a language code from the enum of Languages supported by this translation service. * @param languageName The name of the language, for example, "English" * @return code representing this language, for example, "en", for this translation API * @throws IllegalArgumentException */ public static String toLanguage(String languageName) throws IllegalArgumentException { String standardizedName=languageName.toUpperCase(); standardizedName=standardizedName.replace(' ','_'); standardizedName=standardizedName.replace("(",""); standardizedName=standardizedName.replace(")",""); if (standardizedName.equals("UKRAINIAN")) { standardizedName="UKRANIAN"; } if (standardizedName.equals("NORWEGIAN_BOKMAL")) { standardizedName="NORWEGIAN"; } try { return Language.valueOf(standardizedName).toString(); } catch ( IllegalArgumentException e) { Log.e(TAG,"Not found--returning default language code"); return CaptureActivity.DEFAULT_TARGET_LANGUAGE_CODE; } }
Example 8
From project BabelCraft-Legacy, under directory /src/main/java/com/craftfire/babelcraft/util/managers/.
Source file: TranslationManager.java
23
public String translate(String message,Language langfrom,Language langto){ logging.debug("FROM: " + langfrom); logging.debug("TO: " + langto); Translate.setHttpReferrer("http://www.craftfire.com/"); String translated=null; try { translated=Translate.execute(message,langfrom,langto); } catch ( Exception e) { logging.stackTrace(e.getStackTrace(),Thread.currentThread().getStackTrace()[1].getMethodName(),Thread.currentThread().getStackTrace()[1].getLineNumber(),Thread.currentThread().getStackTrace()[1].getClassName(),Thread.currentThread().getStackTrace()[1].getFileName()); } return translated; }
Example 9
From project BabelCraft-Legacy, under directory /src/main/java/com/craftfire/babelcraft/util/managers/.
Source file: TranslationManager.java
23
public String languageName(String lang){ for ( Language l : Language.values()) { if (lang.toLowerCase().equalsIgnoreCase(l.toString().toLowerCase())) { return util.capitalize(l.name().toLowerCase()); } else if (lang.toLowerCase().equalsIgnoreCase(l.name().toLowerCase())) { return util.capitalize(l.name().toLowerCase()); } } return lang; }
Example 10
From project BabelCraft-Legacy, under directory /src/main/java/com/craftfire/babelcraft/util/managers/.
Source file: TranslationManager.java
23
public Language fromString(String lang){ for ( Language l : Language.values()) { if (lang.toLowerCase().equalsIgnoreCase(l.toString().toLowerCase())) { return l; } else if (lang.toLowerCase().equalsIgnoreCase(l.name().toLowerCase())) { return l; } } return null; }
Example 11
From project BabelCraft-Legacy, under directory /src/main/java/com/craftfire/babelcraft/util/managers/.
Source file: TranslationManager.java
23
public String languageCode(String lang){ for ( Language l : Language.values()) { if (lang.equalsIgnoreCase(l.toString())) { return util.capitalize(l.toString().toLowerCase()); } else if (lang.equalsIgnoreCase(l.name())) { return util.capitalize(l.toString().toLowerCase()); } } return lang; }
Example 12
From project google-api-translate-java, under directory /src/main/java/com/google/api/detect/.
Source file: Detect.java
23
/** * Detects the language of a supplied String. * @param text The String to detect the language of. * @return A DetectResult object containing the language, confidence and reliability. * @throws Exception on error. */ public static DetectResult execute(final String text) throws Exception { validateReferrer(); final URL url=new URL(URL + URLEncoder.encode(text,ENCODING)); final JSONObject json=retrieveJSON(url); return new DetectResult(Language.fromString(json.getJSONObject("responseData").getString("language")),json.getJSONObject("responseData").getBoolean("isReliable"),json.getJSONObject("responseData").getDouble("confidence")); }
Example 13
From project google-api-translate-java, under directory /src/test/java/com/google/api/detect/.
Source file: DetectTest.java
23
@Test public void testDetect() throws Exception { System.out.println("testDetect"); GoogleAPI.setHttpReferrer("http://code.google.com/p/google-api-translate-java/"); DetectResult detectResult=Detect.execute("Hello world"); assertEquals(Language.ENGLISH,detectResult.getLanguage()); assertTrue(detectResult.getConfidence() > 0); }
Example 14
From project Jetwick, under directory /src/main/java/de/jetwick/util/.
Source file: Helper.java
23
public static String translate(String txt,Language fromLanguage,Language toLanguage) throws Exception { txt=workAroundBefore(txt); try { txt=Translate.execute(txt,fromLanguage,toLanguage); } catch ( Exception ex) { txt=Translate.execute(txt,Language.ENGLISH,toLanguage); } return workAroundAfter(txt); }
Example 15
From project Jetwick, under directory /src/main/java/de/jetwick/util/.
Source file: Helper.java
23
public static String[] translateAll(String[] texts,Language[] froms,Language[] tos) throws Exception { String res[]=new String[texts.length]; for (int i=0; i < texts.length; i++) { try { res[i]=translate(texts[i],froms[i],tos[i]); } catch ( Exception ex) { logger.warn("Cannot translate:" + texts[i] + " "+ ex.getMessage()); } } return res; }
Example 16
From project Jetwick, under directory /src/main/java/de/jetwick/util/.
Source file: Statistics.java
23
public void start(Map<String,String> map) throws Exception { String argStr=map.get("optimize"); if (argStr != null) { int segments=1; logger.info("Start optimizing for twindex"); OptimizeResponse rsp=tweetSearch.optimize(tweetSearch.getIndexName(),segments); logger.info("Optimized twindex to " + segments + " segments for "+ rsp.getSuccessfulShards()+ "/"+ rsp.getTotalShards()+ " shards.\n Now uindex"); rsp=tweetSearch.optimize(tweetSearch.getIndexName(),segments); logger.info("Optimized uindex to " + segments + " segments for "+ rsp.getSuccessfulShards()+ "/"+ rsp.getTotalShards()+ " shards."); } argStr=map.get("listTweets"); if (argStr != null) { if ("true".equals(argStr)) argStr="**:*"; List<JUser> list=new ArrayList<JUser>(); long ret=tweetSearch.query(list,new TweetQuery(argStr,false)).getHits().getTotalHits(); logger.info("Found: " + ret + " users. Returned: "+ list.size()); print(list); return; } argStr=map.get("exportNoiseWords"); if (argStr != null) { write(new TreeSet<String>(JTweet.NOISE_WORDS.keySet()),argStr); return; } argStr=map.get("importTags"); if (argStr != null) importTags(map.get("tagFile")); argStr=map.get("clearPropertiesOfTags"); if (argStr != null) clearPropertiesOfTags(); argStr=map.get("readStopAndClear"); if (argStr != null) readStopwords(JTweet.class.getResourceAsStream("noise_words_pt.txt")); argStr=map.get("translate"); if (argStr != null) translate(Language.PORTUGUESE); }
Example 17
From project Jetwick, under directory /src/main/java/de/jetwick/util/.
Source file: Statistics.java
23
public void translate(Language lang) throws Exception { List<String> list=Helper.readFile(Helper.createBuffReader(JTweet.class.getResourceAsStream("lang_det_en.txt"))); Set<String> res=new TreeSet<String>(); Set<String> cache=new LinkedHashSet<String>(); int charCounter=0; for ( String str : list) { if (str.isEmpty() || str.startsWith("//")) continue; str=str.toLowerCase().trim(); charCounter+=str.length(); cache.add(str); if (charCounter > 1500) { try { String gTranslated=Translate.execute(cache.toString(),Language.ENGLISH,lang); for ( String tmp : gTranslated.split(",")) { tmp=tmp.toLowerCase().trim().replaceAll("\\[","").replaceAll("\\]",""); res.add(tmp); } } catch ( Exception ex) { logger.error("Cannot translate " + cache.size() + " lines",ex); } charCounter=0; cache.clear(); } } System.out.println("=======================\n\n"); for ( String str : res) { System.out.println(str); } }
Example 18
public TranslateGoogleAsyncTask(String text,Language sourceLanguage,Language targetLanguage,TextView textView){ this.sourceLanguage=sourceLanguage; this.targetLanguage=targetLanguage; this.text=text; this.textView=textView; }
Example 19
From project multi-translator, under directory /src/com/robtheis/translator/.
Source file: TranslatorGoogle.java
23
/** * Convert the given name of a natural language into a Language from the enum of Languages supported by this translation service. * @param languageName The name of the language, for example, "English" * @return The Language object representing this language * @throws IllegalArgumentException */ private static Language toLanguage(String languageName) throws IllegalArgumentException { String standardizedName=languageName.toUpperCase(); standardizedName=standardizedName.replace(' ','_'); standardizedName=standardizedName.replace("(",""); standardizedName=standardizedName.replace(")",""); if (standardizedName.equals("UKRAINIAN")) { standardizedName="UKRANIAN"; } if (standardizedName.equals("BASQUE")) { return null; } if (standardizedName.equals("NORWEGIAN_BOKMAL")) { standardizedName="NORWEGIAN"; } return Language.valueOf(standardizedName); }
Source: http://www.javased.com/index.php?api=com.google.api.translate.Language
0 Response to "Language Translation in Java Example"
Post a Comment