我想采用某种格式的文本文件。在加载并重新格式化第一个文件后,我想打开第二个文本文件并检查第二个文件是否与第一个重新格式化的文件有任何文本匹配。现在我成功地将第一个文本文件重新格式化为我想要的方式。第一个(重新格式化的)文本文件如下所示:
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
我的代码的一般基础:
**我也试图让这个按钮将文本的最终格式输出到最终的富文本框中。
这是我目前的代码。
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按钮)读入两组List我将使用string.contains(“some_string”)但是在每次我打开一个不同的文件时,这些文件的数量。我不确定如何正确地迭代每个列表中的每个项目以比较字符串(每个'会话'可以是不同的)。我还要将它们合并在一起,并将最终结果添加到另一个List中,并将其写入最终的富文本框。但是,我迷路了,对C#来说还是个新手。任何帮助将不胜感激。
问题:如何比较这两个文本文件,将它们正确地放入列表中,比较两个列表中相似的值,用第二个文件中匹配值中的以下文本替换第一个文件中的值?如果这令人困惑,请告诉我!
提前致谢! :)
答案 0 :(得分:1)
如果列用空格或其他字符分隔,则使用string.Split创建列数组。挑出您想要的列并将其存储在SortedList中(列是键和值),每次添加时都要检查以确保没有添加重复项。一次读取一行第二个文件,foreach读取SortedList键,如果是string.Contains键,将该行标记为具有一个列值。
答案 1 :(得分: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]);
}
}
类似的东西会起作用。