Форум программистов, компьютерный форум, киберфорум
C#: API, боты
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
-5 / 3 / 1
Регистрация: 21.07.2017
Сообщений: 71

Yandex API Translator

04.10.2018, 20:48. Показов 2166. Ответов 0
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Написал переводчик с кешированием уже переведённого текста. В теории все должно работать, но прога выдает Exception: Error.
Причем то же самое с фильмами прокатывает, а с текстом нет.
Можете сказать в чем тут проблема?

Вот код там где фильмы:

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
 
namespace Flyweight
{
    class Movie
    {
        public string Title { get; set; }
        public int Year { get; set; }
        public string Plot { get; set; }
 
        public override string ToString()
        {
            return $"Title: {Title}\nYear: {Year}\n\n{Plot}";
        }
    }
 
    interface ICache<TKey, TValue>
    {
        TValue GetValue(TKey key);
        void AddValue(TKey key, TValue value);
    }
 
    class MovieCache : ICache<string, Movie>
    {
        Dictionary<string, Movie> movies = new Dictionary<string, Movie>();
 
        public Movie GetValue(string key)
        {
            if (movies.ContainsKey(key))
            {
                return movies[key];
            }
            return null;
        }
 
        public void AddValue(string key, Movie value)
        {
            movies.Add(key, value);
        }
    }
 
    class MovieSearchAPI
    {
        readonly string apiUrl = @"http://omdbapi.com/";
        readonly string apiKey = "2c9d65d5";
 
        ICache<string, Movie> cache = new MovieCache();
 
        public Movie Search(string title)
        {
            var movie = cache.GetValue(title);
            if (movie == null)
            {
                Console.WriteLine("Reading data from API...");
 
                var webClient = new WebClient();
                try
                {
                    var result = webClient.DownloadString($"{apiUrl}?apikey={apiKey}&t={title}");
                    dynamic data = JsonConvert.DeserializeObject(result);
                    movie = new Movie
                    {
                        Title = data.Title,
                        Year = data.Year,
                        Plot = data.Plot
                    };
                    cache.AddValue(movie.Title, movie);
                }
                catch (WebException)
                {
                    throw;
                }
                catch (Exception)
                {
                    throw new Exception("Not found!");
                }
            }
            else
            {
                Console.WriteLine("Reading data from cache...");
            }
            return movie;
        }
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            var search = new MovieSearchAPI();
 
            var menuItems = new List<string>
            {
                "Inception",
                "Interstellar",
                "Dunkirk"
            };
 
            while (true)
            {
                Console.Clear();
                Console.WriteLine("Choose the movie: ");
                int index = 1;
                foreach (var item in menuItems)
                {
                    Console.WriteLine($"{index++}) {item}");
                }
 
                Int32.TryParse(Console.ReadLine(), out int number);
                try
                {
                    var movie = search.Search(menuItems[number - 1]);
                    Console.WriteLine(movie);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
 
                Console.WriteLine("\nPress ESC to exit or any key to continue...");
                if (Console.ReadKey(true).Key == ConsoleKey.Escape)
                    break;
            }
        }
    }
}
А вот код переводчика:

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net;
 
namespace Translator_FlyWeight
{
    class Text
    {
        public string Text1 { get; set; }
 
        public override string ToString()
        {
            return $"Text: {Text1}\n";
        }
    }
 
    interface ICache<TKey, TValue>
    {
        TValue GetValue(TKey key);
        void AddValue(TKey key, TValue value);
    }
 
    class TextCache : ICache<string, Text>
    {
        Dictionary<string, Text> text = new Dictionary<string, Text>();
 
        public Text GetValue(string key)
        {
            if (text.ContainsKey(key))
            {
                return text[key];
            }
            return null;
        }
 
        public void AddValue(string key, Text value)
        {
            text.Add(key, value);
        }
    }
 
    class TextSearchAPI
    {
        readonly string apiUrl = @"https://translate.yandex.net/api/v1.5/tr.json/translate";
        readonly string apiKey = "trnsl.1.1.20181004T124645Z.7d59f05290944534.2131c58ec4a9ed818ce3840e655a6a0a28302789";
 
        ICache<string, Text> cache = new TextCache();
 
        public Text Search(string SourceText)
        {
            var text = cache.GetValue(SourceText);
            if (text == null)
            {
                Console.WriteLine("Reading data from API...");
 
                var webClient = new WebClient();
                try
                {
                    var result = webClient.DownloadString($"{apiUrl}?key={apiKey}&text={SourceText}&lang=en-ru&format=plain");
                    dynamic data = JsonConvert.DeserializeObject(result);
                    text = new Text
                    {
                        Text1 = data
                    };
                    cache.AddValue(text.Text1, text);
                }
                catch (WebException)
                {
                    throw;
                }
                catch (Exception)
                {
                    throw new Exception("Error!");
                }
            }
            else
            {
                Console.WriteLine("Reading data from cache...");
            }
            return text;
        }
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            var search = new TextSearchAPI();
 
            //Console.WriteLine("Enter text to translate:");
            //string text2 = "Hello";
 
            //try
            //{
            //    var text = search.Search(text2);
            //    Console.WriteLine(text);
            //}
            //catch (Exception ex)
            //{
            //    Console.WriteLine(ex.Message);
            //}
 
            var menuItems = new List<string>
            {
                "Inception"
            };
 
            while (true)
            {
                Console.Clear();
                Console.WriteLine("Choose the movie: ");
                int index = 1;
                foreach (var item in menuItems)
                {
                    Console.WriteLine($"{index++}) {item}");
                }
 
                Int32.TryParse(Console.ReadLine(), out int number);
                try
                {
                    var text = search.Search(menuItems[number - 1]);
                    Console.WriteLine(text);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
 
                Console.WriteLine("\nPress ESC to exit or any key to continue...");
                if (Console.ReadKey(true).Key == ConsoleKey.Escape)
                    break;
            }
        }
    }
}
Добавлено через 13 минут
Проблема вроде как в кеше, а точнее в его ключе. Но как решить проблему не знаю

Добавлено через 56 минут
Проблема решена. Я просто добавил новую отдельную переменную специально для ключа.

Вот код:
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
 
namespace Translator_FlyWeight
{
    class Text
    {
        public string Text1 { get; set; }
        public string Key { get; set; }
 
        public override string ToString()
        {
            return $"Text: {Text1}\n";
        }
    }
 
    interface ICache<TKey, TValue>
    {
        TValue GetValue(TKey key);
        void AddValue(TKey key, TValue value);
    }
 
    class TextCache : ICache<string, Text>
    {
        Dictionary<string, Text> text = new Dictionary<string, Text>();
 
        public Text GetValue(string key)
        {
            if (text.ContainsKey(key))
            {
                return text[key];
            }
            return null;
        }
 
        public void AddValue(string key, Text value)
        {
            text.Add(key, value);
        }
    }
 
    class TextSearchAPI
    {
        readonly string apiUrl = @"https://translate.yandex.net/api/v1.5/tr.json/translate";
        readonly string apiKey = "trnsl.1.1.20181004T124645Z.7d59f05290944534.2131c58ec4a9ed818ce3840e655a6a0a28302789";
 
        ICache<string, Text> cache = new TextCache();
 
        public Text Search(string SourceText)
        {
            var text = cache.GetValue(SourceText);
            if (text == null)
            {
                Console.WriteLine("Reading data from API...");
 
                var webClient = new WebClient();
                try
                {
                    var result = webClient.DownloadString($"{apiUrl}?key={apiKey}&text={SourceText}&lang=en");
                    dynamic data = JsonConvert.DeserializeObject(result);
                    text = new Text
                    {
                        Key = SourceText,
                        Text1 = Convert.ToString(data)
                    };
                    cache.AddValue(text.Key, text);
                }
                catch (WebException)
                {
                    throw;
                }
                catch (Exception)
                {
                    throw new Exception("Not found!");
                }
            }
            else
            {
                Console.WriteLine("Reading data from cache...");
            }
            return text;
        }
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            var search = new TextSearchAPI();
 
            while (true)
            {
                Console.Clear();
                Console.WriteLine("Enter text to translate from Russian to English:");
                var text2 = Console.ReadLine();
 
                try
                {
                    var text = search.Search(text2);
                    Console.WriteLine(text);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
 
                Console.WriteLine("\nPress ESC to exit or any key to continue...");
                if (Console.ReadKey(true).Key == ConsoleKey.Escape)
                    break;
            }
        }
    }
}
0
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
04.10.2018, 20:48
Ответы с готовыми решениями:

Microsoft Translator: как перевести большой объем текста
пишу парсер, парсер занаганяет в переводчик текст с HTML тегами, эсли статти малинкие всё отлично, эсли большые тогда проблема. Использую...

VK API как обойти ограничение api vk.com в 1000 человек?
Добрый день. У меня есть вопрос - как получить больше 1000 человек в запросе на поиск людей? while (true) { ...

Microsoft Translator Java API
в связи с закрытием бесплатного API google translate пытаюсь прикрутить аналог от мелкомягких (bing translator). ссыль на исходники и...

0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
04.10.2018, 20:48
Помогаю со студенческими работами здесь

Yandex api.directory.yandex.net создание почтового ящика
Добрый день. Пишу скрипт для создания почтовых ящиков на Яндекс.Коннект с использованием API...

Yandex API
Добрый день форумчанам! Просьба откликнуться имеющим опыт в написании Яндекс API приложений. Ну или другим гуру =) Итак, необходимо...

Авторизация в Yandex, API
Доброй ночи уважаемые программисты! Уже который день бьюсь головой об стол, не могу авторизоваться в Yandex средствами delphi (RX) ...

Yandex REST API
Здравствуйте! Разбираюсь с Yandex REST API. Я смог разобраться, как работать через get-запросы, например вот так: HttpURLConnection...

API Yandex переводчик
Учусь работать с JSON и для практики решил написать переводчик на основе API Яндекс переводчика. JSON строку получить получается, а...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
1
Ответ Создать тему
Новые блоги и статьи
Первый деплой
lagorue 16.01.2026
Не спеша развернул своё 1ое приложение в kubernetes. А дальше мне интересно создать 1фронтэнд приложения и 2 бэкэнд приложения развернуть 2 деплоя в кубере получится 2 сервиса и что-бы они. . .
Расчёт переходных процессов в цепи постоянного тока
igorrr37 16.01.2026
/ * Дана цепь постоянного тока с R, L, C, k(ключ), U, E, J. Программа составляет систему уравнений по 1 и 2 законам Кирхгофа, решает её и находит токи на L и напряжения на C в установ. режимах до и. . .
Восстановить юзерскрипты Greasemonkey из бэкапа браузера
damix 15.01.2026
Если восстановить из бэкапа профиль Firefox после переустановки винды, то список юзерскриптов в Greasemonkey будет пустым. Но восстановить их можно так. Для этого понадобится консольная утилита. . .
Изучаю kubernetes
lagorue 13.01.2026
А пригодятся-ли мне знания kubernetes в России?
Сукцессия микоризы: основная теория в виде двух уравнений.
anaschu 11.01.2026
https:/ / rutube. ru/ video/ 7a537f578d808e67a3c6fd818a44a5c4/
WordPad для Windows 11
Jel 10.01.2026
WordPad для Windows 11 — это приложение, которое восстанавливает классический текстовый редактор WordPad в операционной системе Windows 11. После того как Microsoft исключила WordPad из. . .
Classic Notepad for Windows 11
Jel 10.01.2026
Old Classic Notepad for Windows 11 Приложение для Windows 11, позволяющее пользователям вернуть классическую версию текстового редактора «Блокнот» из Windows 10. Программа предоставляет более. . .
Почему дизайн решает?
Neotwalker 09.01.2026
В современном мире, где конкуренция за внимание потребителя достигла пика, дизайн становится мощным инструментом для успеха бренда. Это не просто красивый внешний вид продукта или сайта — это. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru