[英]How to Convert plain text data into managed format?
使用C#的目標是創建一個可以正常工作的應用程序,該應用程序將接受文本文件作為輸入,進行讀取,並將該文本文件中的數據部分分為不同的組,這些組包含索引#和該部分的名稱在本節的第一部分中找到。
這可能是關於如何在純文本文件中獲取數據,將其分成數據“組”部分的問題。 並以某種托管格式輸出文件。
文本輸入文件有13個字段,然后是狀態的另一個字段,即14個字段。
文本輸入文件將包含大約1500-2000組數據節,因此將最多索引2000個條目,並且條目名稱為第一個字段,即“包名稱”。 一段數據將是這樣的:
Package: horse
Version: 1.2.3
Depends: libgcc
Provides:
Status: user installed
Other: other info
Other2: other info 2
Package: cow
Version: 2.3.4
Depends: libhay
Provides: milk
Status: user installed
Other: white with black spots
Other2: has a red cow bell around her neck
Package: tractor
Version: 0.9.22
Depends: diesel
Provides:
等等...
如何讀取數據並將其放入適當的表或條目或數據集中?
ps感謝您的上一次編輯
一種簡單的解決方案是一次讀取一行文件,在“:”處拆分,然后將每個文件存儲在Dictionary<string, string>
,后者本身存儲在Package
然后將其添加到List<Package>
。 只要您獲得關鍵字“ Package”,就創建一個新的Package
實例並將其添加到列表中。 下面的代碼可以達到目的,但並不是很安全。
static void Main(string[] args)
{
string line;
List<Package> packages = new List<Package>();
Package package = null;
StreamReader file = new System.IO.StreamReader("TextFile1.txt");
while ((line = file.ReadLine()) != null)
{
string[] pair = line.Split(new string[] { ": " }, StringSplitOptions.None);
if (pair.Length != 2)
continue;
if (pair[0] == "Package")
{
package = new Package();
packages.Add(package);
}
package.Values.Add(pair[0].Trim(), pair[1].Trim());
}
file.Close();
Console.WriteLine(packages.Count);
foreach (Package p in packages)
{
Console.WriteLine(p);
foreach (KeyValuePair<string, string> pair in p.Values)
Console.WriteLine("{0}={1}", pair.Key, pair.Value);
}
Console.ReadLine();
}
}
class Package
{
public Dictionary<string, string> Values;
public Package()
{
Values = new Dictionary<string, string>();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.