Yandex translator java api

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

A simple REST client library for Yandex.Translate

License

vbauer/yandex-translate-api

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

yandex-translate-api is a simple REST client library for Yandex.Translate. The API provides access to the Yandex online machine translation service. It supports more than 90 languages and can translate separate words or complete texts.

Online documentation: Javadoc

The following actions are required to work with this library:

repositories < maven < url "https://jitpack.io" > > dependencies < compile 'com.github.vbauer:yandex-translate-api:1.4.2' >
repository> id>jitpack.ioid> url>https://jitpack.iourl> repository> dependency> groupId>com.github.vbauergroupId> artifactId>yandex-translate-apiartifactId> version>1.4.2version> dependency>
  • Groovy language is used in the examples just to simplify them.
  • Additional documentation about the official Yandex.Translate API could be found here: https://tech.yandex.com/translate/doc/dg/concepts/api-overview-docpage/

The entry point of this library is YTranslateApi interface (and the corresponding implementation YTranslateApiImpl ).

def key = "" def api = new YTranslateApiImpl(key)

Using instance of this service you can work with the following features:

  • DetectionApi detects the language of the specified text.
  • LanguageApi returns a list of translation directions supported by the service.
  • TranslationApi allows to translate text from one language to another.
Читайте также:  Css 500 кму характеристики

The following example returns Language.EN :

def language = api.detectionApi().detect("Hello, World!")

To retrieve all available languages without their names, use the following code snippet:

def languages = api.languageApi().all()

It is also possible to fetch names for each language, using ui parameter:

def languages = api.languageApi().all(Language.RU)

The following code should translate Russian’s «Как дела?» to some English variant ( «How are you doing?» or something similar):

def translation = api.translationApi().translate( "Как дела?", Direction.of(Language.RU, Language.EN) )

Source language could be also detected automatically (so you need to specify only target language):

def translation = api.translationApi().translate("Как дела?", Language.EN)
  • Yandex LLC and all their developers for the great service.
  • Vyacheslav Rusakov for the following Gradle plugins: gradle-java-lib-plugin and gradle-quality-plugin.

Источник

Яндекс-Перевод в терминале через Java

Используя API переводчика написал для себя простую программу для перевода слов и фраз, и чтобы из любого места работало. Хотел использовать curl, но непонятно почему получал ошибку что такого языка нет.

Теперь вместо скучного, а иногда медленного, а иногда такого ярко-белого нового таба с лишней информацией пишу в терминале trans hello и получаю перевод на русский, а если trans привет — на английский. Разумеется можно вводить и фразы, в кавычках. Работает быстренько.

import javax.net.ssl.HttpsURLConnection; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLEncoder; public class YandexTranslate < private static int i = 0; public static void main(String[] args) throws IOException < System.out.println(translate("ru", args[0])); >private static String translate(String lang, String input) throws IOException < String urlStr = "https://translate.yandex.net/api/v1.5/tr.json/translate?key=trnsl.1.1.20150627T071448Z.117dacaac1e63b79.6b1b4bb84635161fcd400dace9fb2220d6f344ef"; URL urlObj = new URL(urlStr); HttpsURLConnection connection = (HttpsURLConnection)urlObj.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream()); dataOutputStream.writeBytes("text=" + URLEncoder.encode(input, "UTF-8") + "&lang=" + lang); InputStream response = connection.getInputStream(); String json = new java.util.Scanner(response).nextLine(); int start = json.indexOf("["); int end = json.indexOf("]"); String translated = json.substring(start + 2, end - 1); i++; if (translated.equals(input) && i < 2) < // if return equal of entered text - we need change direction of translation return translate("en", input); >else return translated; > > 

Чтобы перевод работал в любой директории, нужно в /usr/bin положить .class-файл и trans.sh для его вызова:

#!/bin/bash if [ $# -eq 0 ] then echo "Enter text for translate" exit 1; fi java -classpath /usr/bin/ YandexTranslate "$1" 

И сделать его исполняемым: sudo chmod +x trans.sh

Если вы вместо перевода начнете получать сообщение о том что ключ кончился, или мало-ли-что — тут можно получить новый кей — вставьте его куда надо в Java-коде, после чего откомпилируйте (javac YandexTranslate.java) и скопируйте с заменой на /usr/bin.

Также пользователи Firefox могут воспользоваться моим экстеншеном-переводчиком — он интегрирован в контекстное меню, быстрый-минималистичный и не оказывает влияния на DOM, после установки сразу работает и не требует рестарта браузера. На данный момент единственный Яндекс-переводчик для текущих версий Firefox.

UPD: Такие штуки лучше делать сразу на баше, но сразу у меня не получилось, но после того как bockra показал свой скрипт, я его дописал — чтобы не надо было указывать направление перевода, и можно без ковычек писать сразу несколько слов. Так и не смог добиться перевода нескольких слов с амперсантом, но и халера с ним.

#!/bin/bash # # simple console util for translation text to any language using Yandex Translate API # use: trans 'call me, baby # will return translation of a phrase to ru or en language # more example at http://api.yandex.ru/translate/ # input=$ link='https://translate.yandex.net/api/v1.5/tr.json/translate?key=trnsl.1.1.20150627T071448Z.117dacaac1e63b79.6b1b4bb84635161fcd400dace9fb2220d6f344ef&lang=' function translate() < translated=$(curl -s "$link$key&lang=$1&text=$input" | awk -F'"' ) > translate "ru" if [ "$translated" == "$input" ] then translate "en" fi echo $translated 

Источник

Читайте также:  Javascript определить текущую страницу

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

JAVA wrapper for Yandex translate api (https://tech.yandex.com/translate)

License

huymluu/yandex-translate-api

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Yandex Translate API usage

YandexTranslator yandexTranslator = new YandexTranslator("YOUR YANDEX API KEY");
ListLanguage> supportedLanguages = yandexTranslator.getSupportedLanguages();
// Translate single term - explicit 'from' & 'to' languages String translated = yandexTranslator.translate("Hello world", Language.ENGLISH, Language.GERMAN); // Translate single term - auto detect 'from' language String translated = yandexTranslator.translate("Hello world", Language.GERMAN); // Translate list of terms ListString> input = new ArrayListString>(); input.add("Hello"); input.add("World"); ListString> translated = yandexTranslator.translate(input, Language.GERMAN);
// Auto detect best language Language detectedLanguage = yandexTranslator.detectLanguage("Hello world"); // Detect best language with hint Language detectedLanguage = yandexTranslator.detectLanguage("Hallo", Language.GERMAN); // Detect best language with multiple hint Language detectedLanguage = yandexTranslator.detectLanguage("Hallo", Language.ENGLISH, Language.GERMAN);

Yandex Dictionary API usage

YandexDictionary yandexDictionary = new YandexDictionary("YOUR YANDEX API KEY");

Get supported lookup directions

MapLanguage, ListLanguage>> directions = yandexDictionary.getSupportedTranslateDirections();
// Simple lookup ListDefinition> definitions = yandexDictionary.lookup("time", Language.ENGLISH, Language.GERMAN); // Lookup with flags (not sure what it means, read https://tech.yandex.com/dictionary/doc/dg/reference/lookup-docpage/) ListDefinition> definitions = yandexDictionary.lookup("time", Language.ENGLISH, Language.GERMAN, LookupFlag.FAMILY, LookupFlag.MORPHO, LookupFlag.POS_FILTER);

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Java wrapper for the Yandex.Translate machine translation web service API

License

freakwave666/yandex-translator-java-api

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Читайте также:  Css and div tag

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Provides a Java wrapper around the Yandex machine translation web service API.

Currently, only the services for translating a single string and detecting the language of a single string are implemented in this API. The translate/detect services are not implemented for an array of strings, and the getLangs service is not implemented.

This project was adapted from the microsoft-translator-java-api project by Jonathan Griggs.

import com.rmtheis.yandtran.language.Language; import com.rmtheis.yandtran.translate.Translate; public class test < public static void main(String[] args) throws Exception < Translate.setKey("[Put your API Key here]"); String translatedText = Translate.execute("Hola, mundo!", Language.SPANISH, Language.ENGLISH); System.out.println(translatedText); > >

This project is licensed under the Apache License, Version 2.0

About

Java wrapper for the Yandex.Translate machine translation web service API

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Проект на Java по использованию API Yandex Translator.

UsenkoKonstantinVL/yandex-translator

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Программа переводчик с английского на русский на Java с использованием API Yandex Переводчика.

Для корректной сборки данного проекта требуется Gradle версии 3+ и Java 8. Для сборки нужно в командной строке выполнить команду gradle build . Скомпилированный JAR файл будет находиться в \\build\libs и именоваться yandex-translator-x.x.x.jar

About

Проект на Java по использованию API Yandex Translator.

Источник

Оцените статью