2011-06-24 88 views
2

我想采用某种格式的一个文本文件。第一个文件加载并重新格式化后,我想打开第二个文本文件并检查第二个文件是否与第一个重新格式化文件有任何文本匹配。现在我成功地将第一个文本文件重新格式化为我想要的格式。第(格式化)文本文件是这样的:C# - 使用两个.txt文件比较/替换文本

1  0010 12345    DEF, DEF-0320     
    1  0020 ABC-00010G   ABC-A,1xx,10%,x1x,0603   
    1  0020A ABC-00010G   ABC-A,1xx,10%,x1x,0603   
    1  0030A ABC-00127G   ABC,4.7xx,10%,x1x,0805 
    . 
    . 
    . 

我想知道如何在这个文件中(上图),找到第二列(0010,0020 0020A,0030A,...)和比较它/在第二个文本文件中搜索它。第二个文本文件的格式将是这个样子:

10 BARE PCB 
    20 T C40, C3112 
    B D5, D45, D48 
    30 B R25 
    . 
    . 
    . 

一旦我能够从第一个文件(0010,0020 0020A,0030A)与第二档(10,20找到了比赛, B,30)我想抓住10,20,B,30之后的行,并用它们替换第一个文件0010,0020,0020A,0030A。另外,如果第一个数字不以“A”(即0010)结尾,我想在新文件的末尾加上“T”。但是,如果它以“A”(即0030A)结尾,我想在文件末尾加上“B”。另外,对于格式为“C40”(或类似格式)的第二个文件中的每个值,如果存在多个(由“,”分隔)并且复制上面行中的相同信息。这意味着它应该是这样的:

1  AAAA BCD 12345    DEF, DEF-0320     T 
    1  C40  ABC-00010G   ABC-A,1xx,10%,x1x,0603  T 
    1  C3112  ABC-00010G   ABC-A,1xx,10%,x1x,0603  T 
    1  D5  ABC-00010G   ABC-A,1xx,20%,x1x,0603  B 
    1  D45  ABC-00010G   ABC-A,1xx,20%,x1x,0603  B 
    1  D48  ABC-00010G   ABC-A,1xx,20%,x1x,0603  B 
    1  R25  ABC-00127G   ABC,4.7xx,100%,x1x,0805  B 

我的代码一般基础:

  • 打开按钮:打开一个txt文件。
  • 保存按钮:保存新的格式化文本文件,我想将其保存到。
  • 清除按钮:清除我使用的所有富文本框中的文本。
  • OpenRefs按钮:打开使用的第一个文件比较的第二个txt文件**

**我也试图让这个按钮,输出文本的最终格式进入决赛富文本。框。

这是我目前的代码。

using System; 
    using System.Collections.Generic; 
    using System.ComponentModel; 
    using System.Data; 
    using System.Drawing; 
    using System.Linq; 
    using System.Text; 
    using System.Windows.Forms; 
    using System.IO; 
    using System.Diagnostics; 
    using System.Text.RegularExpressions; 

    namespace Formatter 
    { 
     public partial class Form : Form 
     { 
      // Create a OpenFileDialog to request a path and file name to open. 
      OpenFileDialog openFile = new OpenFileDialog(); 
      OpenFileDialog openRefs = new OpenFileDialog(); 

      public Form() 
      { 
      InitializeComponent(); 
      } 

      private void openButton_Click(object sender, EventArgs e) 
      { 
      // Initialize the OpenFileDialog to specify the .txt extension as well as 
      // its intial directory for the file. 
      openFile.DefaultExt = "*.txt"; 
      openFile.Filter = ".txt Files|*.txt"; 
      openFile.InitialDirectory = "C:\\"; 
      openFile.RestoreDirectory = true; 

      try 
      { 
       // Open the contents of the file into the originalTextRichTextBox. 
       if (openFile.ShowDialog() == DialogResult.OK && openFile.FileName.Length > 0) 
        originalTextRichTextBox.LoadFile(openFile.FileName, RichTextBoxStreamType.PlainText); 

       // Throws a FileNotFoundException otherwise. 
       else 
        throw new FileNotFoundException(); 

       // Resets the formattedTextRichTextBox so multiple files aren't loaded on top of eachother. 
       formattedTextRichTextBox.ResetText(); 

       foreach (string line in File.ReadAllLines(openFile.FileName)) 
       { 
        // Uses regular expressions to find a line that has, digit(s), space(s), digit(s) + letter(s), 
        // space(s), digit(s), space(s), any character (up to 25 times). 
        Match theMatch = Regex.Match(line, @"^[\.*\d]+\s+[\d\w]+\s+[\d\-\w*]+\s+.{25}"); 

        if (theMatch.Success) 
        { 
         // Stores the matched value in string output. 
         string output = theMatch.Value; 

         // Sets the formattedTextRichTextBox to the string output. 
         formattedTextRichTextBox.AppendText(output); 
         formattedTextRichTextBox.AppendText("\n"); 
        } 
       } 
      } 

      // Catches an exception if the file was not opened. 
      catch (Exception) 
      { 
       MessageBox.Show("There was not a specified file path.", "Path Not Found Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); 
      } 
      } 

      private void saveButton_Click(object sender, EventArgs e) 
      { 
      // Create a SaveFileDialog to request a path and file name to save. 
      SaveFileDialog saveFile = new SaveFileDialog(); 

      // Initialize the SaveFileDialog to specify the .txt extension for the file. 
      saveFile.DefaultExt = "*.txt"; 
      saveFile.Filter = ".txt Files|*.txt"; 
      saveFile.InitialDirectory = "C:\\"; 
      saveFile.RestoreDirectory = true; 

      try 
      { 
       // Save the contents of the formattedTextRichTextBox into the file. 
       if (saveFile.ShowDialog() == DialogResult.OK && saveFile.FileName.Length > 0) 
        formattedTextRichTextBox.SaveFile(saveFile.FileName, RichTextBoxStreamType.PlainText); 

       // Throws a FileNotFoundException otherwise. 
       else 
        throw new FileNotFoundException(); 
      } 

      // Catches an exception if the file was not saved. 
      catch (Exception) 
      { 
       MessageBox.Show("There was not a specified file path.", "Path Not Found Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); 
      } 
      } 

      private void clearButton_Click(object sender, EventArgs e) 
      { 
      try 
      { 
       // Resets the text in all of the boxes. 
       originalTextRichTextBox.ResetText(); 
       formattedTextRichTextBox.ResetText(); 
       refsTextRichTextBox.ResetText(); 
       finalTextRichTextBox.ResetText(); 
      } 

      // Catches an exception if the either text box could not be cleared. 
      catch (Exception) 
      { 
       MessageBox.Show("Could not clear the text.", "Clearing Text Box Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); 
      } 
      } 

      private void openRefsButton_Click(object sender, EventArgs e) 
      { 
      // Initialize the OpenFileDialog to specify the .txt extension as well as 
      // its intial directory for the file. 
      openRefs.DefaultExt = "*.txt"; 
      openRefs.Filter = ".txt Files|*.txt"; 
      openRefs.InitialDirectory = "C:\\"; 
      openRefs.RestoreDirectory = true; 

      try 
      { 
       // Open the contents of the file into the originalTextRichTextBox. 
       if (openRefs.ShowDialog() == DialogResult.OK && openRefs.FileName.Length > 0) 
        refsTextRichTextBox.LoadFile(openRefs.FileName, RichTextBoxStreamType.PlainText); 

       // Throws a FileNotFoundException otherwise. 
       else 
        throw new FileNotFoundException(); 


       // ******************************************** 
       // ******************************************** 
       // ******************************************** 
       // FROM HERE DOWN IS WHERE I NEED THE HELP! :) 
       // ******************************************** 
       // ******************************************** 
       // ******************************************** 
       string[] refLines = System.IO.File.ReadAllLines(openRefs.FileName); 

       foreach (string line in refLines) 
       { 
        finalTextRichTextBox.AppendText(line + "\n"); 
       } 

       try 
       { 
        using (StreamReader readRefs = new StreamReader(openRefs.FileName)) 
        { 
         originalTextRichTextBox.ResetText(); 

         List<string> refFileLines = new List<string>(); 

         while (!readRefs.EndOfStream) 
         { 
         refFileLines.Add(readRefs.ReadLine()); 
         } 

         using (StreamReader readFile = new StreamReader(openFile.FileName)) 
         { 
         List<string> fileLines = new List<string>(); 

         while (!readFile.EndOfStream) 
         { 
          fileLines.Add(readFile.ReadLine()); 
         } 
         } 

         refFileLines.Contains(""); 
        } 
       } 

       catch (Exception) 
       { 
        MessageBox.Show("Could not read file.", "Read File Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); 
       } 
      } 

      // Catches an exception if the file was not opened. 
      catch (Exception) 
      { 
       MessageBox.Show("There was not a specified file path.", "Path Not Found Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); 
      } 
      } 
     } 
    } 

我在做什么方面有点失落。我试图把每行代码存储在一个字符串列表中,并且一旦我将两个文件(打开按钮和openrefs按钮)读入到两组列表中,我将使用string.contains(“some_string”),但是数字可能每次打开一个不同的文件的文件。我不确定如何通过每个列表中的每个项目来比较字符串(这可以是不同的'会话')。我也打算将它们联合起来,并将最终结果添加到另一个List中,并将其写入最终的富文本框。但是,我迷路了,对C#来说很新。任何帮助将不胜感激。

问题:如何比较这两个文本文件,将它们正确放入列表中,比较两个相似值列表,将第一个文件中的值替换为第二个文件中的匹配值中的以下文本文件?如果这是令人困惑的,请告诉我!

在此先感谢! :)

回答

1

如果您的列使用空格或其他字符分隔,请使用string.Split创建一个列数组。选择你想要的列并将其存储在SortedList中(列是键和值),每次添加时都要检查以确保不添加重复项。每次读取第二个文件一行,对SortedList键进行foreach,如果string.Contains键,则将该行标记为具有某个列值。

+0

好吧,我正在使用string.Split ..这是我为那一步的代码。 string [] finalText = refsTextRichTextBox.Text.Split('');foreach(finalText中的字符串行){finalTextRichTextBox.AppendText(line +“\ n”);} ----这会在最后一个富文本框中用新行上的每个值打印出来。然而,当我使用我的代码:Match numberMatch = Regex.Match(finalTextRichTextBox.Text,@“^ [\ d] +”); originalTextRichTextBox.AppendText(numberMatch +“\ n”); ---打印输出仅在新生产线上显示数字“10”。它似乎只抓住第一条价值线而不是全部..? – theNoobGuy

+0

你使用Regex.Match来试图完成什么?我没有理由将它用于你想要做的任何事情。我已经向您展示了如何进行基本的列匹配。你剩下的具体问题是什么? –

+0

我使用正则表达式来仅匹配只有数行..当我把它分解,它看起来像: BARE PCB 牛逼 C40 乙 ...... 但我要抢10,20等,然后在第一个文件中找到这些值。一旦我在那里找到它们,我想获取“C3”格式(即下面的字母和数字)的值,并使用新的正则表达式在文件1中使用string.contains,它找到“C3 “格式化的行来替换string.contains项目。如果这有道理?我是C#的新手,我不确定我是否确切地理解了如何在“答案”文本中说出你所说的话。 – theNoobGuy

1

我并没有真正获得记录的格式,因为你说你正在分割一个空格,但是你的记录不能正确地分割。如果你的文件是一个固定长度的文件,那么你可以使用.substring来拉出数据。如果我正在阅读你的问题,我想你会想要读取第一个文件的每一行,并将该行添加到哈希集中,将第二列作为关键字,然后将该行的其余部分作为值。然后循环遍历第二个文件,并且对于该行中的每个值,找到它所使用的键,并将该键的值与刚刚读取的行的值一起打印出来。然后,您可以找到一个地方添加一个条件,如果该键具有“A”或最后不打印“T”。我认为你应该远离正则表达式,因为表现通常是缺乏的,我不认为这是你需要的。

 string strFileName = DisplayFile("Please Select File 1", ".txt", null); 

     StreamReader srInput = File.OpenText(strFileName); 

     Hashtable newHash = new Hashtable(); 

     while(srInput.Peek > -1) 
     { 
      string temp = srInput.ReadLine(); 
      string parts = temp.Split('//put delimiter here'); 

      newHash.Add(parts[1]//your key should be your second column     value,parts    [2]//this is your value); 

     } 

//然后在您的第二个文件中读取并测试每一行以查看它是否在第一个文件中有匹配。

 string strFileName2 = DisplayFile("Please Select File 2", ".txt", null); 

    StreamReader srInput2 = File.OpenText(strFileName); 

    while(srInput2.Peek > -1) 
    { 
    string temp2 = srInput.Readline(); 
    string[] parts2 = temp2.Split('delim'); 

    if(newHash.ContainsKey(parts[whichever is the column you want to check is])) 
    { 
     //then print to value to new file or list 
     //newList.Add(parts[that were checked] + newHash[parts that were checked]); 
    } 
    } 

这样的事情会起作用。

+0

不幸的是该文件不是固定的长度。 :(我很熟悉正则表达式,而不是用其他方式编码,这也是不幸的!我正在努力学习:)。我如何将第一个文件存储到哈希集中,并将第二列作为关键字,其余列作为值?我对此不熟悉...... – theNoobGuy