Форум программистов, компьютерный форум, киберфорум
C# для начинающих
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.88/219: Рейтинг темы: голосов - 219, средняя оценка - 4.88
9 / 9 / 2
Регистрация: 14.07.2010
Сообщений: 166
1

Переводчик

11.01.2011, 13:21. Показов 43946. Ответов 5
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Char;
 
namespace ConsoleApplication1
 
{
    class Calc
    {
        static void Main()
        {
            Dictionary<string, string> trans = new Dictionary<string, string>();
 
       Add(string, string):
          trans.Add("хорошо", "good");
          trans.Add("привет", "hello");
          trans.Add("утро","morning");
                Console.ReadKey();
 
        }    
    }
}
Только начал изучать Сшарп, помогите у меня вот такие вопросы:
1- словать создал, методом Add заполнил, а как теперь читалть из словаря?
2- как можно реализовать добавлением пользователем новых слов?

код писать мне не обязательно, хотябы отдельные примеры строк))
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
11.01.2011, 13:21
Ответы с готовыми решениями:

Переводчик с английского
Приложение переводит текст с английского на русский и обратно. Нужно сделать так, чтобы можно было...

Приложение переводчик
Здравствуйте, есть приложение, которое переводит текст с русского на англ. и обратно, есть словарь...

Яндекс переводчик
Здравствуйте. Возник вопрос: Подскажите как получить ответ от сервера в любом случае Написал...

Переводчик ASM в bytes[]
Понадобилось делать инжект asm кода в процесс, но каждый раз смотреть код через CE не удобно....

5
1319 / 992 / 127
Регистрация: 08.12.2009
Сообщений: 1,299
11.01.2011, 14:05 2
1.
C#
1
string translation = trans["хорошо"];
2. ну в данном случае можно написать так:
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using System;
using System.Collections.Generic;
 
namespace ConsoleApplication1 {
    class Calc {
 
        private static Dictionary<string, string> trans = new Dictionary<string, string>();
 
        static void Main() {
 
            trans.Add("хорошо", "good");
            trans.Add("привет", "hello");
            trans.Add("утро", "morning");
            Console.ReadKey();
 
        }
 
        public static void Add(string key, string value) {
            trans.Add(key, value);
        }
 
    }
}
НО, 1) лучше бы всё таки связаться с ООП, а то на шарпе это творение не смотрится: создай приложение Windows Forms - многое упростится. заодно по началу забудешь страшное слово static
2) Dictionary<,> - односвязен: по переводу русское слово не узнаешь. лучше делать самому, в своем классе
0
339 / 285 / 62
Регистрация: 02.09.2010
Сообщений: 547
11.01.2011, 14:43 3
Вот, написал как сам вижу консольный словарь. Переводит с русского на английский, реализовано добавление слов и собственно перевод из слов забитых в словарь.Может пригодится:

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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace Dict
 
{      
    class Diction
    {
        string rus;
        string engl;
        public string Rus
        {
            get
            {
                return rus;
            }
            set
            {
                rus = value;
            }
        }
        public string Engl
        {
            get
            {
                return engl;
            }
            set
            {
                engl = value;
            }
        }
        public Diction(string Rus1, string Engl1)
        {
            Rus = Rus1;
            Engl = Engl1;
        }
       
        public override string ToString()
        {
            return string.Format("Перевод:"+Engl);
        }
    }
    class Program
 
    {
        static void Nahod(Diction d1,string s1)
        {
            if (s1 == d1.Rus)
                Console.WriteLine(d1.ToString());
        }
        static void Main(string[] args)
        {
            List<Diction> Dict = new List<Diction>();
            string s1;
            string s2;
            do
            {
                Console.WriteLine("Введите русское слово или 'q' для выхода из режима добавления слов");
                s1 = Console.ReadLine();
                if (s1 == "q") break;
                Console.WriteLine("Введите английское значение слова");
                s2 = Console.ReadLine();
                Dict.Add(new Diction(s1, s2));
            } while (s1 != "");
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("Введите русское слово для перевода");
            string s3 = Console.ReadLine();
            foreach (Diction dic in Dict)
            {
                Nahod(dic, s3);
            }
            Console.ReadKey();
        }
                 
        
    }
}
0
133 / 133 / 29
Регистрация: 17.09.2010
Сообщений: 288
11.01.2011, 15:51 4
yardie, вот тоже могу поделиться, правда переводит с русского на украинский и обратно:
Form1.cs

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
#region Переменные.
        ToolTip toolTip = new ToolTip();
 
        List<string> textToolTip = new List<string>()
        {
            "Доавить в словарь.", "Просмотр словаря.", "Перевести слово.", "Выбор языка перевода."
        };
        List<string> ruLang = new List<string>();
        List<string> ukrLang = new List<string>();
        #endregion
 
        #region Инициализация программы.
        public DictionaryForm()
        {
            InitializeComponent();
        }
 
        private void DictionaryForm_Load(object sender, EventArgs e)
        {
            langComboBox.SelectedIndex = 0;
 
            ruLang.AddRange(File.ReadAllLines("ru.txt"));
            ukrLang.AddRange(File.ReadAllLines("ukr.txt"));
        }
        #endregion
 
        #region Отображаем всплывающую подсказку.
        private void AddButton_MouseEnter(object sender, EventArgs e)
        {
            toolTip.Active = true;
 
            if (sender == AddButton)
            {
                toolTip.Show(textToolTip[0], AddButton);
 
                return;
            }
 
            if (sender == viewDictionaryButton)
            {
                toolTip.Show(textToolTip[1], viewDictionaryButton);
 
                return;
            }
 
            if (sender == translateButton)
            {
                toolTip.Show(textToolTip[2], translateButton);
 
                return;
            }
        }
 
        private void MouseLeave_Button(object sender, EventArgs e)
        {
            toolTip.Active = false;
        }
 
        private void langComboBox_MouseEnter(object sender, EventArgs e)
        {
            toolTip.Active = true;
 
            toolTip.Show(textToolTip[3], langComboBox);
        }
 
        private void langComboBox_MouseLeave(object sender, EventArgs e)
        {
            toolTip.Active = false;
        }
        #endregion
 
        #region Добавляем слово в словарь.
        private void AddButton_Click(object sender, EventArgs e)
        {
            NewWord newWord = new NewWord();
            if (newWord.AddWord() == DialogResult.OK & newWord.wordTextBox.Text != "" & newWord.translateTextBox.Text != "")
            {
                ruLang.Add(newWord.wordTextBox.Text);
                ukrLang.Add(newWord.translateTextBox.Text);
 
                File.WriteAllLines("ru.txt", ruLang);
                File.WriteAllLines("ukr.txt", ukrLang);
            }
        }
        #endregion
 
        #region Отображаем словарь.
        private void viewDictionaryButton_Click(object sender, EventArgs e)
        {
            ViewDictionary viewDictionary = new ViewDictionary();
        }
        #endregion
 
        #region Переводим слово.
        private void translateButton_Click(object sender, EventArgs e)
        {
            translateTextBox.Text = null;
 
            Translate tanslate = new Translate(wordTextBox.Text, translateTextBox, langComboBox.SelectedIndex);
        }
        #endregion

class NewWord

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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
 
namespace Словарь
{
    public partial class NewWord
    {
        public TextBox wordTextBox;
        public TextBox translateTextBox;
 
        public DialogResult AddWord()
        {
            #region Создаем форму.
            Form wordForm = new Form();
            wordForm.StartPosition = FormStartPosition.CenterScreen;
            wordForm.FormBorderStyle = FormBorderStyle.Fixed3D;
            wordForm.Size = new Size(250, 180);
            wordForm.MinimizeBox = false;
            wordForm.MaximizeBox = false;
            wordForm.Text = "Новое слово";
            #endregion
 
            #region Создаем метки.
            Label wordLabel = new Label();
            wordLabel.Location = new Point(10, 10);
            wordLabel.AutoSize = false;
            wordLabel.Size = new Size(230, 25);
            wordLabel.Font = new Font("Times New Roman", 12, FontStyle.Bold);
            wordLabel.Text = "Слово: ";
 
            Label translateLabel = new Label();
            translateLabel.Location = new Point(10, 60);
            translateLabel.AutoSize = false;
            translateLabel.Size = new Size(230, 25);
            translateLabel.Font = new Font("Times New Roman", 12, FontStyle.Bold);
            translateLabel.Text = "Перевод: ";
            #endregion
 
            #region Создаем текстовые поля.
            wordTextBox = new TextBox();
            wordTextBox.Location = new Point(10, 35);
            wordTextBox.Size = new Size(215, 25);
            wordTextBox.Text = null;
 
            translateTextBox = new TextBox();
            translateTextBox.Location = new Point(10, 85);
            translateTextBox.Size = new Size(215, 25);
            translateTextBox.Text = null;
            #endregion
 
            #region Создаем кнопки.
            Button okButton = new Button();
            okButton.Location = new Point(80, 115);
            okButton.Size = new Size(70, 25);
            okButton.DialogResult = DialogResult.OK;
            okButton.Text = "OK";
 
            Button cancelButton = new Button();
            cancelButton.Location = new Point(155, 115);
            cancelButton.Size = new Size(70, 25);
            cancelButton.DialogResult = DialogResult.Cancel;
            cancelButton.Text = "Cancel";
            #endregion
 
            #region Добавляем на форму компоненты и отображаем саму форму.
            wordForm.Controls.Add(wordLabel);
            wordForm.Controls.Add(translateLabel);
            wordForm.Controls.Add(wordTextBox);
            wordForm.Controls.Add(translateTextBox);
            wordForm.Controls.Add(okButton);
            wordForm.Controls.Add(cancelButton);
            wordLabel.Show();
            translateLabel.Show();
            wordTextBox.Show();
            translateTextBox.Show();
            okButton.Show();
            cancelButton.Show();
            wordForm.ShowDialog();
            #endregion
 
            return wordForm.DialogResult;
        }
    }
}

class ViewDictionary

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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
 
namespace Словарь
{
    public partial class ViewDictionary
    {
        string[] ruText = new string[File.ReadAllLines("ru.txt").Length];
        string[] ukrText = new string[File.ReadAllLines("ukr.txt").Length];
 
        public ViewDictionary()
        {
            #region Создаем форму.
            Form viewDictionaryForm = new Form();
            viewDictionaryForm.StartPosition = FormStartPosition.CenterScreen;
            viewDictionaryForm.FormBorderStyle = FormBorderStyle.Fixed3D;
            viewDictionaryForm.Size = new Size(250, 185);
            viewDictionaryForm.MinimizeBox = false;
            viewDictionaryForm.MaximizeBox = false;
            viewDictionaryForm.Text = "Просмотр словаря";
            #endregion
 
            #region Создаем RichTextBox.
            RichTextBox richText = new RichTextBox();
            richText.Location = new Point(10, 10);
            richText.Size = new Size(215, 105);
            richText.ScrollBars = RichTextBoxScrollBars.ForcedVertical;
            richText.ReadOnly = true;
            for (int i = 0; i < ruText.Length; i++)
            {
                ruText[i] = File.ReadAllLines("ru.txt")[i];
                ukrText[i] = File.ReadAllLines("ukr.txt")[i];
                richText.AppendText(ruText[i] + " - " + ukrText[i] + "\n");
            }
            viewDictionaryForm.Controls.Add(richText);
            #endregion
 
            #region Создаем кнопку.
            Button closeButton = new Button();
            closeButton.Location = new Point(150, 120);
            closeButton.Size = new Size(75, 25);
            closeButton.Text = "Закрыть";
            closeButton.DialogResult = DialogResult.OK;
            viewDictionaryForm.Controls.Add(closeButton);
            #endregion
 
            viewDictionaryForm.ShowDialog();
        }
    }
}

class Translate

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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
 
namespace Словарь
{
    public partial class Translate
    {
        string[] ru = new string[File.ReadAllLines("ru.txt").Length];
        string[] ua = new string[File.ReadAllLines("ukr.txt").Length];
 
        public Translate(string word, TextBox textBox, int index)
        {
            #region Переводим с русского.
            if (index == 0)
            {
                for (int i = 0; i < ru.Length; i++)
                {
                    ru[i] = File.ReadAllLines("ru.txt")[i];
                    ua[i] = File.ReadAllLines("ukr.txt")[i];
 
                    if (ru[i].Equals(word, StringComparison.CurrentCultureIgnoreCase))
                    {
                        textBox.Text = ua[i];
 
                        return;
                    }
                }
            }
            #endregion
 
            #region Переводим с украинского.
            if (index == 1)
            {
                for (int i = 0; i < ua.Length; i++)
                {
                    ua[i] = File.ReadAllLines("ukr.txt")[i];
                    ru[i] = File.ReadAllLines("ru.txt")[i];
 
                    if (ua[i].Equals(word, StringComparison.CurrentCultureIgnoreCase))
                    {
                        textBox.Text = ru[i];
 
                        return;
                    }
                }
            }
            #endregion
        }
    }
}
Вложения
Тип файла: rar Словарь.rar (51.4 Кб, 501 просмотров)
1
339 / 285 / 62
Регистрация: 02.09.2010
Сообщений: 547
12.01.2011, 12:22 5
Переделываю для себя переводчик приведенный выше, и компилятор выдет ошибку:

"В экземпляре объекта не задана ссылка на объект."
Не понимаю что не так.Вот кусок кода где выдается ошибка

C#
1
2
3
4
5
6
7
8
9
10
11
private void buttonAdd_Click(object sender, EventArgs e)
        {
            Newword newWord = new Newword();
            if (newWord.textBox3.Text != "" && newWord.textBox4.Text != "")//Здесь ошибка
            {
                ruLang.Add(newWord.textBox3.Text);
                enLang.Add(newWord.textBox4.Text);
                File.WriteAllLines(@"C:\rus.txt", ruLang.ToArray());
                File.WriteAllLines(@"C:\en.txt", enLang.ToArray());
            }
        }
класс Newword

C#
1
2
3
4
5
6
7
8
9
namespace Upr
{
    public partial class Newword
    {
        public TextBox textBox3;
        public TextBox textBox4;
     
    }
}
Добавлено через 3 минуты
Вернее ошибка вылетает, после того как пытаешся добавить слово.т.е. после нажатия кнопки

Добавлено через 1 час 40 минут
Проблему решил, изменив класс:

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
namespace Upr
{
    public partial class Newword
    {
        public string rus;
        public string engl;
 
        public Newword(string rus, string engl)
        {
            this.rus = rus;
            this.engl = engl;
        }
     
    }
}
и код кнопки
C#
1
2
3
4
5
6
7
8
9
10
11
12
 private void buttonAdd_Click(object sender, EventArgs e)
        {
            Newword newWord = new Newword(textBox3.Text,textBox4.Text);
            
            if (newWord.rus != "" && newWord.engl != "")
            {
                ruLang.Add(newWord.rus);
                enLang.Add(newWord.engl);
                File.WriteAllLines(@"C:\rus.txt", ruLang.ToArray());
                File.WriteAllLines(@"C:\en.txt", enLang.ToArray());
            }
        }
0
3 / 2 / 0
Регистрация: 06.07.2013
Сообщений: 9
26.08.2013, 23:19 6
Переводчик на C# (WPF), который тянет данные с Яндекс.API, и его короткое описание
Вложения
Тип файла: zip WpfYaTranslator.zip (299.0 Кб, 571 просмотров)
1
26.08.2013, 23:19
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
26.08.2013, 23:19
Помогаю со студенческими работами здесь

Яндекс переводчик API
string a = &quot;answer &quot;; var answer = &quot;&quot;; var get = new HttpRequest(); ...

1337(Leet) переводчик
Всем доброго времени суток вот на досуге решил сделать leet переводчик, я использовал исходник от...

Переводчик, использующий Google Translate
Здраствуйте. Как сделать перевод с русского на английский и обратно используя интернет соединение...

Переводчик с подключением Яндекс API
Консольное приложение. Задача такая. Входной файл - input.txt, в котором текст на каком либо...


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

Или воспользуйтесь поиском по форуму:
6
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru