如何将文本(来自txt文件,例如englishWord.txt)附加到所有行的末尾(来自另一个txt文件,例如PolishWord.Txt)?

时间:2018-11-27 21:52:48

标签: c#

如何将文本(来自txt文件,例如englishWord.txt)附加到所有行的末尾(来自另一个txt文件,例如PolishWord.Txt)? 我有一个带有许多英语单词的txt文件,而在另一个txt文件中翻译了波兰语单词。我希望结果是这样的:

englishWord.txt:

Via (Phantom2 d a) (Phantom1 d a)

polishWord.txt:

familiar
involve
ability
expand

程序使result.txt像这样:

znajomy
angażować
umiejętność
rozszerzać

感谢您的关注。我期待着您的回复。 对不起,我的英语不好。

这是我尝试过的:

familiar - znajomy
involve - angazować
ability - umiejętność
expand - rozszerzac

3 个答案:

答案 0 :(得分:0)

一个简单的方法是首先从两个文件中读取该行,将这些行按空格分成两个数组,然后同时遍历这些数组。即:

System.IO.StreamReader english = new System.IO.StreamReader("englishWord.txt");
System.IO.StreamReader polish = new System.IO.StreamReader("polishWord.txt");

String englishLine = english.ReadLine();
String polishLine = polish.ReadLine();
String englishWords[] = englishLine.split(' ');
String polishWords[] = polishLine.split(' ');

for (int i = 0; i < englishWords.Length; i++) {
    /* Output englishWords[i] and polishWords[i] to result.txt here */
}

希望这会有所帮助!

答案 1 :(得分:0)

尝试一下:

using (var english = new StreamReader("englishWord.txt"))
using (var polish = new StreamReader("polishWord.txt"))
using (var result = new StreamWriter("result.txt"))
{
    while (!english.EndOfStream && !polish.EndOfStream)
    {
        result.Write(english.ReadLine());
        result.Write(" - ");
        result.Write(polish.ReadLine());
        result.WriteLine();
    }
}

答案 2 :(得分:0)

这将产生与规范中完全相同的结果。但是,如果您要构建像字典这样的东西,我建议您使用其他格式,例如写入Excel文件或csv文件。

        //load files
        var englishFile = File.OpenText("englishWord.txt").ReadToEnd();
        var polishFile = File.OpenText("polishWord.txt").ReadToEnd();

        //convert to string arrays
        var englishArray = englishFile.Split(' ');
        var polishArray = polishFile.Split(' ');

        //build output string
        String outputString = "";
        //take the lenght of the shorter array in case they're not the same length
        int maxLength = Math.Min(englishArray.Length, polishArray.Length);
        for (int i=0; i<maxLength; i++)
        {
            outputString += englishArray[i] + " - " + polishArray[i] + " ";
        }

        //write output to file
        File.WriteAllText("results.txt", outputString);