- feanor777 / Dictionary.java
- Saved searches
- Use saved searches to filter your results more quickly
- License
- demidko/aot
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
- Подробно про словарь на Java
- Декларация
- Конструктор
- Методы класса util.Dictionary
- Добавить и поместить значения в словарь
- Возвращаемые значения в словаре
- Получить метод для извлечения значений, сопоставленных с ключом
- Проверьте, пустой ли словарь
- Удаление значения ключа из словаря в Java
- Реализация словаря в Java
feanor777 / Dictionary.java
Написать программу переводчик, которая будет переводить текст, написанный на одном языке, на другой язык согласно заранее составленному словарю. Сделать ф-ю ручного наполнения словаря и возможность его сохранения на диск.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
import java . io . FileInputStream ; |
import java . io . FileOutputStream ; |
import java . io . IOException ; |
import java . io . ObjectInputStream ; |
import java . io . ObjectOutputStream ; |
import java . io . Serializable ; |
import java . util . HashMap ; |
import java . util . Map ; |
public class Dictionary implements Serializable |
private static final long serialVersionUID = 1L ; |
protected Map < String , String >dictionary ; |
public Dictionary () |
dictionary = new HashMap < String , String >(); |
> |
public void addWord ( String english , String russia ) |
dictionary . put ( english , russia ); |
> |
public Map < String , String >getDictionary () |
return dictionary ; |
> |
public void save ( String path ) |
try ( FileOutputStream fos = new FileOutputStream ( path ); |
ObjectOutputStream oos = new ObjectOutputStream ( fos )) |
oos . writeObject ( dictionary ); |
> catch ( IOException e ) |
e . printStackTrace (); |
> |
> |
public void load ( String path ) |
try ( FileInputStream fis = new FileInputStream ( path ); |
ObjectInputStream ois = new ObjectInputStream ( fis )) |
dictionary = ( Map < String , String >) ois . readObject (); |
> catch ( IOException | ClassNotFoundException e ) |
e . printStackTrace (); |
> |
> |
> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
import java . util . Map ; |
import java . util . Map . Entry ; |
import java . util . Scanner ; |
import java . util . Set ; |
public class Main |
public static void main ( String [] args ) |
Scanner scan = new Scanner ( System . in ); |
Dictionary dictionary = new Dictionary (); |
Translator translator ; |
Menu menu = new Menu (); |
int solution ; |
do |
menu . show (); |
solution = scan . nextInt (); |
switch ( solution ) |
case 1 : |
System . out . println ( «Enter english word:» ); |
String english = new Scanner ( System . in ). nextLine (); |
System . out . println ( «Enter translate:» ); |
String russia = new Scanner ( System . in ). nextLine (); |
dictionary . addWord ( english , russia ); |
break ; |
case 2 : |
System . out . println ( «Enter english sentence:» ); |
String englishSentence = new Scanner ( System . in ). nextLine (); |
translator = new Translator ( dictionary ); |
translator . TranslateEnglishToRussia ( englishSentence ); |
break ; |
case 3 : |
System . out . println ( «Enter russia sentence:» ); |
String russiaSentence = new Scanner ( System . in ). nextLine (); |
translator = new Translator ( dictionary ); |
translator . TranslateRussiaToEnglish ( russiaSentence ); |
break ; |
case 4 : |
System . out |
. println ( «Enter path to save dictionary(EXAMPLE d: \\ java \\ dictionary.txt):» ); |
String path = new Scanner ( System . in ). nextLine (); |
dictionary . save ( path ); |
break ; |
case 5 : |
System . out |
. println ( «Enter path to load dictionary(EXAMPLE d: \\ java \\ dictionary.txt):» ); |
path = new Scanner ( System . in ). nextLine (); |
path . replace ( » \\ » , » \\ \\ » ); |
dictionary . load ( path ); |
break ; |
case 6 : |
if ( dictionary . getDictionary (). size () == 0 ) |
System . out |
. println ( «Your dictionary is empty! Please add word or load dictionary from file.» ); |
else System . out . println ( dictionary . getDictionary ()); |
break ; |
default : |
if ( solution != 0 ) |
System . out . println ( «Invalid choose!» ); |
break ; |
> |
> while ( solution != 0 ); |
> |
> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
public class Menu |
public void show () |
System . out . println ( » \n \t \t MENU» ); |
System . out . println ( «Enter: » ); |
System . out . println ( «1 : Add word to dictionary» ); |
System . out . println ( «2 : Translate from English to Russia» ); |
System . out . println ( «3 : Translate from Russia to English» ); |
System . out . println ( «4 : Save dictionary» ); |
System . out . println ( «5 : Load dictionary» ); |
System . out . println ( «6 : Show dictionary» ); |
System . out . println ( «0 : Exit» ); |
> |
> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
import java . util . Map ; |
import java . util . Set ; |
public class Translator |
Set < Map . Entry < String , String >> vocabularySet ; |
public Translator ( Dictionary dictionary ) |
vocabularySet = dictionary . getDictionary (). entrySet (); |
> |
public void TranslateEnglishToRussia ( String phrase ) |
String [] str = phrase . split ( » » ); |
for ( int i = 0 ; i < str . length ; i ++) |
int j = 0 ; |
if ( i == 0 ) |
System . out . println (); |
> |
for ( Map . Entry < String , String >entry : vocabularySet ) |
if ( entry . getKey (). equalsIgnoreCase ( str [ i ])) |
System . out . print ( entry . getValue () + » » ); |
break ; |
> |
else if ( j == vocabularySet . size () — 1 ) |
System . out . print ( str [ i ] + » » ); |
> |
j ++; |
> |
> |
> |
public void TranslateRussiaToEnglish ( String phrase ) |
String [] str = phrase . split ( » » ); |
for ( int i = 0 ; i < str . length ; i ++) |
int j = 0 ; |
if ( i == 0 ) |
System . out . println (); |
> |
for ( Map . Entry < String , String >entry : vocabularySet ) |
if ( entry . getValue (). equalsIgnoreCase ( str [ i ])) |
System . out . print ( entry . getKey () + » » ); |
break ; |
> |
else if ( j == vocabularySet . size () — 1 ) |
System . out . print ( str [ i ] + » » ); |
> |
j ++; |
> |
> |
> |
> |
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.
Russian morphology for Java / Морфологический словарь русского языка для Java
License
demidko/aot
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
Aot – автоматическая обработка текста
Java библиотека для быстрого (!) получения леммы и морфологической информации по заданному слову русского языка. Реинкарнация aot-lematizier с удобным обновленным API, избавленная от closed-source зависимостей, упрощенная для сборки, и как следствие легко подключаемая в другие проекты с помощью репозитория Jitpack. Поддерживает все версии Java начиная с 8-ой версии, а также протестирована со всеми версиями Kotlin начиная с 1.5.*
- Определяет исходную форму слова согласно правилам русского языка, так называемую лемму (первое лицо, единственное число).
- Определяет всевозможные характеристики слова, такие как часть речи, род, падеж, число и т. д.
- Определяет всевозможные преобразования слова с их характеристиками (flexion).
- Различает слова с полным соответствием письменной формы, но разной морфологией, например замок (что? строение) и замок (что сделал? замок под дождем).
- Различает омонимии, то есть слова с полным соответствием и письменной формы и морфологии, но различным смыслом, например замок (что? строение) и замок (что? запор).
Вам понадобится Gradle или Maven, или другая система сборки.
import java.io.IOException; import static java.lang.System.out; import static com.github.demidko.aot.WordformMeaning.lookupForMeanings; class Example < public static void main(String[] args) throws IOException < var meanings = lookupForMeanings("люди"); out.println(meanings.size()); /* 1 */ out.println(meanings.get(0).getMorphology()); /* [С, мр, им, мн] */ out.println(meanings.get(0).getLemma()); /* человек */ for (var t : meanings.get(0).getTransformations()) < out.println(t.toString() + " " + t.getMorphology()); /* * человек [С, мр, им, ед] * человека [рд, С, мр, ед] * человеку [С, мр, ед, дт] * человека [С, мр, ед, вн] * человеком [тв, С, мр, ед] * человеке [С, мр, ед, пр] * люди [С, мр, им, мн] * людей [рд, С, мр, мн] * человек [рд, С, мр, мн] * людям [С, мр, мн, дт] * человекам [С, мр, мн, дт] * людей [С, мр, мн, вн] * людьми [тв, С, мр, мн] * человеками [тв, С, мр, мн] * людях [С, мр, мн, пр] * человеках [С, мр, мн, пр] */ > > >
Откуда взяты слова и морфология?
За слова и морфологическую информацию спасибо проекту morph_dict. Из него и были взяты исходные mrd и tab файлы словарей. Документация для них лежит здесь. В нашей java-библиотеке, эти исходные словари скомпилированы в бинарный формат, более удобный для быстрой загрузки в память и поиска. В качестве общего стандарта для библиотеки и компилятора, используется библиотека aot-bytecode.
About
Russian morphology for Java / Морфологический словарь русского языка для Java
Подробно про словарь на Java
Словарь в Java – это абстрактный класс, который является родителем любого класса, использующего отношения пары ключ-значение. В этом блоге мы узнаем больше о классе Dictionary в Java и познакомимся с различными методами.
Словарь – это абстрактный класс, представляющий хранилище ключей / значений, которое работает как Map. Вы можете сохранить значение в объекте Dictionary и, как только оно будет сохранено, вы можете получить его, используя его ключ.
Декларация
публичный абстрактный класс Dictionary расширяет Object.
Конструктор
Методы класса util.Dictionary
Проверка размера словаря. size(): java.util.Dictionary.size() возвращает количество пар ключ-значение в словаре
Синтаксис: public abstract int size()
Добавить и поместить значения в словарь
put (ключ K, значение V): java.util.Dictionary.put (ключ K, значение V) добавляет пару ключ-значение в словарь
Синтаксис: public abstract V put(K key, V value)
Возвращаемые значения в словаре
elements(): java.util.Dictionary.elements() возвращает представление значения в словаре.
Синтаксис: public abstract Enumeration elements()
Получить метод для извлечения значений, сопоставленных с ключом
get (Object key): java.util.Dictionary.get (Object key) возвращает значение, которое сопоставлено с ключом в словаре.
Синтаксис: public abstract V get(Object key)
Проверьте, пустой ли словарь
isEmpty(): java.util.Dictionary.isEmpty() проверяет, является ли словарь пустым или нет.
Синтаксис: public abstract boolean isEmpty()
Вернуть true, если в словаре нет отношения ключ-значение; иначе вернуть ложь.
Удаление значения ключа из словаря в Java
remove (Object key): java.util.Dictionary.remove (Object key) удаляет пару ключ-значение, сопоставленную с ключом.
Синтаксис: public abstract V remove(Object key)
Реализация словаря в Java
import java.util.*; public class My_Class < public static void main(String[] args) < // Initializing a Dictionary Dictionary edu = new Hashtable(); // put() method edu.put("1000", "Edureka"); edu.put("2000", "Platfrom"); // elements() method : for (Enumeration i = edu.elements(); i.hasMoreElements();) < System.out.println("Value in Dictionary : " + i.nextElement()); >// get() method : System.out.println("nValue at key = 3000 : " + edu.get("2000")); System.out.println("Value at key = 1000 : " + edu.get("2000")); // isEmpty() method : System.out.println("nThere is no key-value pair : " + edu.isEmpty() + "n"); // keys() method : for (Enumeration k = edu.keys(); k.hasMoreElements();) < System.out.println("Keys in Dictionary : " + k.nextElement()); >// remove() method : System.out.println("nRemove : " + edu.remove("1000")); System.out.println("Check the value of removed key : " + edu.get("1000")); System.out.println("nSize of Dictionary : " + edu.size()); > >
Value in Dictionary : Edureka
Value in Dictionary : Platform
Value at key = 3000 : null
Value at key = 1000 : Platform
There is no key-value pair : false
Keys in Dictionary : 1000
Keys in Dictionary : 2000
Remove : Edureka
Check the value of removed key : null
Size of Dictionary : 1