如何解析文件中的文本?

What Should I Do To Parse Text Inside A File?

我想读取info1.txt文件并想在另一个文本文件info2.txt中写入这种方式。

Id      Name     Address      DOB      Phone
1       abcd      efg      1/16/2021  987654323
2       hijkl     mno      2/16/2021  678987652

info1.txt文件内容如下:

Id:1
Name:abcd
Address:efg
DOB:1/16/2021 3:31:22 PM
Phone:987654323

info2.txt 就像上面提到的 table 格式一样,也想删除“3:31:22 PM”。我为解决这个问题开发的代码块如下:

static void Main(string[] args)
{
    FileStream fsRead = new FileStream("E:\info1.txt", FileMode.Open, FileAccess.Read);
    StreamReader srObj = new StreamReader(fsRead);
    FileStream fsWrite = new FileStream("E:\info2.txt", FileMode.Create, FileAccess.Write);
    StreamWriter swObj = new StreamWriter(fsWrite);

    while (srObj.Peek() > 0)
    {
        string str;
        string[] strArray;
        
        str = srObj.ReadLine();
        str = str.Replace(" 3:31:22 PM", "");
        strArray = str.Split(':');

        if (strArray.Length > 1)
        {
            swObj.Write(strArray[1]);
            swObj.Write(" ");
        }
    }
    
    swObj.Close();
    fsWrite.Close();
    srObj.Close();
    fsRead.Close();

    Console.ReadKey();
}

我会将文件解析为字典列表,其中每个字典的键都是列。

首先将文件行分割成一个字符串数组。您可以为此使用 File.ReadAllLines。然后将数组发送到这个解析行的函数。

public static List<Dictionary<string, string>> Parse(string [] lines)
{
    List<Dictionary<string, string>> data = new List<Dictionary<string, string>>();
    Dictionary<string, string> temp = new Dictionary<string, string>();
    foreach (var line in lines) {
        var parts = line.Split(new[] { ':' }, 2);
        if (parts.Length == 2) {
            temp[parts[0]] = parts[1];
        }
        else {
            if (temp.Count > 0) data.Add(temp);
            temp = new Dictionary<string, string>();
        }
    }
    if (temp.Count > 0) data.Add(temp);
    return data;
}

然后,制作一个将列表写入文件的函数。

public static void PrintTable(List<Dictionary<string, string>> users, TextWriter stream)
{
    if (users.Count == 0) return;
    
    // Print the header line
    foreach(var pair in users[0]) {
        stream.Write("{0,-12}", pair.Key);
    }
    stream.WriteLine();
    
    foreach (var user in users) {
        foreach(var pair in user) {
            // Special handling for DOB
            if (pair.Key == "DOB") stream.Write("{0,-12}", pair.Value.Split(' ')[0]);
            else stream.Write("{0,-12}", pair.Value);
        }
        stream.WriteLine();
    }
}