C # как поместить текстовый файл из openFileDialog в массив scriptFile [] [] по строке #, и содержимое строки строки - PullRequest
0 голосов
/ 06 июня 2018

Я пытаюсь создать инструмент в C #.С помощью этого инструмента пользователь может построчно просматривать текст на иностранном языке и вводить его в текстовом поле ниже, отправлять и в конечном итоге сохранять в новый текстовый файл.

Я пытаюсь открыть файл .txt с openFileDialog, а затем отправить построчно через цикл for, который добавит в двумерный массив 4 вещи:

Things we need:
        Array scriptFile[][]
            scriptFile[X][0] = Int holding the Line number
            scriptFile[X][1] = First line piece
            scriptFile[X][2] = Untranslated Text
            scriptFile[X][3] = Translated Text input

Первая часть массиваномер строки в целом числе.Второй и третий фрагменты - это 2 фрагмента текста, разделенных табуляцией.

Example Text File:
Dog 슈퍼 지방입니다.
cat 일요일에 빨간색입니다.
Elephant    적의 피로 위안을 찾는다.
Mouse   그의 백성의 죽음을 복수하기 위해 싸우십시오.
racoon  즉시 의료 지원이 필요합니다.

Что тогда:

So array: 
scriptFile[0][0] = 1
scriptFile[0][1] = Dog
scriptFile[0][2] = 슈퍼 지방입니다.
scriptFile[0][3] = "" (Later input as human translation)

Если я смогу это взломать, то все остальное просто встанет на свои местамгновенно.Я продолжаю искать решения, но мои знания C # ограничены, так как я в основном парень по Java / PHP: /

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

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.continueButton.Click += new System.EventHandler(this.continueButton_Click);
        }
        private void continueButton_Click(object sender, EventArgs e)
        {
            if (openFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                System.IO.StreamReader sr = new System.IO.StreamReader(openFile.FileName);
                var lineCount = File.ReadLines(openFile.FileName).Count();
                MessageBox.Show(lineCount.ToString());
                sr.Close();
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            openFile.Filter = "Text files (.txt)|*.txt";
        }
    }

Ответы [ 3 ]

0 голосов
/ 06 июня 2018

Вероятно, эффекта обучения нет, но я понял это.

ПРИМЕЧАНИЕ Это очень сырой код.Нет обработки исключений.

using System;
using System.IO;
using System.Threading.Tasks;  
using System.Windows.Forms;

namespace TextArrayManipulation
{ 
    public partial class Form1 : Form
    {
        private TaskCompletionSource<string> _translationSubmittedSource = new TaskCompletionSource<string>();

        private string[,] _result;

        public Form1()
        {
            InitializeComponent();
        }

        private async void buttonOpen_Click(object sender, EventArgs e)
        {
            using (var ofd = new OpenFileDialog())
            {
                if (ofd.ShowDialog() != DialogResult.OK) return;

                _result = new string[File.ReadLines(openFile.FileName).Count(), 4];

                using (var streamReader = new StreamReader(ofd.FileName))
                {
                    var line = string.Empty;
                    var lineCount = 0;
                    while (line != null)
                    {
                        line = streamReader.ReadLine();

                        if (string.IsNullOrWhiteSpace(line)) continue;

                        // update GUI
                        textBoxLine.Text = line;
                        labelLineNumber.Text = lineCount.ToString();

                        // wait for user to enter a translation
                        var translation = await _translationSubmittedSource.Task;

                        // split line at tabstop
                        var parts = line.Split('\t');
                        // populate result
                        _result[lineCount, 0] = lineCount.ToString();
                        _result[lineCount, 1] = parts[0];
                        _result[lineCount, 2] = parts[1];
                        _result[lineCount, 3] = translation;

                        // reset soruce
                        _translationSubmittedSource = new TaskCompletionSource<string>();
                        // clear TextBox
                        textBoxTranslation.Clear();
                        // increase line count
                        lineCount++;
                    }
                }
                // proceede as you wish...
            }
        }

        private void buttonSubmit_Click(object sender, EventArgs e)
        {
            _translationSubmittedSource.TrySetResult(textBoxTranslation.Text);
        }
    }
}
0 голосов
/ 06 июня 2018

Ну, вы уже получили два полных ответа, но я все равно опубликую свой дубль, может быть, это поможет найти правильное решение.

public void Main()
{
    List<LineOfText> lines = ReadTextFile("file.txt");

    // Use resulting list like this
    if (lines.Count > 0)
    {
        foreach (var line in lines)
        {
            Console.WriteLine($"[{line.LineNumber}] {line.FirstLinePiece}\t{line.UntranslatedText}");
        }
    }
}

class LineOfText
{
    public int LineNumber { get; set; }
    public string FirstLinePiece { get; set; }
    public string UntranslatedText { get; set; }
    public string TranslatedText { get; set; }
}

private List<LineOfText> ReadTextFile(string filePath)
{
    List<LineOfText> array = new List<LineOfText>();

    using (StreamReader sr = new StreamReader(filePath))
    {
        // Read entire file and split into lines by new line or carriage return symbol
        string[] lines = sr.ReadToEnd().Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
        // Parse each line and add to the list
        for (int i = 0; i < lines.Length; i++)
        {
            int tabIndex = lines[i].IndexOf('\t');
            string firstPiece = lines[i].Substring(0, tabIndex);
            string restOfLine = lines[i].Substring(tabIndex + 1);

            array.Add(new LineOfText()
            {
                LineNumber = i,
                FirstLinePiece = firstPiece,
                UntranslatedText = restOfLine
            });
        }
    }

    return array;
}
0 голосов
/ 06 июня 2018

Я бы посоветовал сделать ваши переводы классными, в долгосрочной перспективе это послужит вам намного лучше.Очень базовая реализация класса может выглядеть примерно так:

public class Translation
{
    public int Id { get; set; }
    public string Text { get; set; }
    public string TranslatedText { get; set; }

    public Translation()
    {

    }

    public IEnumerable<Translation> ReadTranslationFile(string TranslationFileName)
    {
        var translations = new List<Translation>();

        //implement reading in text file

        return translations;
    }

    public void WriteTranslationFile(string TranslationFileName, List<Translation> Translations)
    {
        //implement writing file
    }
}
...