簡體   English   中英

C#:循環遍歷文本文件,將其拆分並打印新的文本文件

[英]C#: Loop over Textfile, split it and Print a new Textfile

我得到了很多像這樣的String行作為輸入。 輸入是一個字符串,來自

theObjects.Runstate;

每個@VAR; ****; @ ENDVAR; 代表循環中的一行和一步。

@VAR;Variable=Speed;Value=Fast;Op==;@ENDVAR;@VAR;Variable=Fabricator;Value=Freescale;Op==;@ENDVAR;

我將其拆分,以刪除不需要的字段,例如@ VAR,@ ENDVAR和Op ==。 最佳輸出為:

Speed = Fast; 
Fabricator = Freescale; and so on.

我可以刪除@VAR和the @ ENDVAR。 切掉“ Op ==”不會那么難,所以現在這不是問題的主要重點。 我現在最擔心的是,我想將輸出打印為文本文件。 要打印一個數組,我必須遍歷它。 但是在每次迭代中,當我得到新的一行時,我都會用當前的拆分字符串覆蓋Array。 我認為Inputfile的最后一行是一個空的String,所以我得到的Output只是一個空的Text-File。 如果有人可以幫助我,那將是很好的。

string[] w;
Textwriter tw2;
foreach (EA.Element theObjects in myPackageObject.Elements)
{
    theObjects.Type = "Object";
    foreach (EA.Element theElements in PackageHW.Elements)
    {
        if (theObjects.ClassfierID == theElements.ElementID)
        {
            t = theObjects.RunState;
            w = t.Replace("@ENDVAR;", "@VAR;").Replace("@VAR;", ";").Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);

            foreach (string s in w)
            {
                tw2.WriteLine(s);
            }
        }
    }
}

此linq查詢給出了預期的結果:

var keyValuePairLines = File.ReadLines(pathInputFile)
    .Select(l =>
    {
        l = l.Replace("@VAR;", "").Replace("@ENDVAR;", "").Replace("Op==;", "");
        IEnumerable<string[]> tokens = l.Split(new[]{';'}, StringSplitOptions.RemoveEmptyEntries)
            .Select(t => t.Split('='));
        return tokens.Select(t => {
            return new KeyValuePair<string, string>(t.First(), t.Last());
        });
    });

foreach(var keyValLine in keyValuePairLines)
    foreach(var keyVal in keyValLine) 
        Console.WriteLine("Key:{0} Value:{1}", keyVal.Key, keyVal.Value);

輸出:

Key:Variable         Value:Speed
Key:Value            Value:Fast
Key:Variable         Value:Fabricator
Key:Value            Value:Freescale

如果要輸出到另一行帶有一對鍵值對的文本文件,請執行以下操作:

File.WriteAllLines(pathOutputFile, keyValuePairLines.SelectMany(l => 
    l.Select(kv => string.Format("{0}:{1}", kv.Key, kv.Value))));

根據您在評論中的問題進行編輯

“為了使輸出像這樣,我必須更改/添加什么。我需要AttributeValuePairs,例如:Speed = Fast;或Fabricator = Freescale?”

現在,我了解了邏輯,您有鍵值對,但您僅對值感興趣。 因此,每兩個鍵值都屬於一個,一對中的第一個值指定屬性,第二個值指定該屬性的值(fe Speed = Fast)。

然后稍微復雜一點:

var keyValuePairLines = File.ReadLines(pathInputFile)
    .Select(l =>
    {
        l = l.Replace("@VAR;", "").Replace("@ENDVAR;", "").Replace("Op==;", "");
        string[] tokens = l.Split(new[]{';'}, StringSplitOptions.RemoveEmptyEntries);
        var lineValues = new List<KeyValuePair<string, string>>();
        for(int i = 0; i < tokens.Length; i += 2)
        {
            // Value to a variable can be found on the next index, therefore i += 2
            string[] pair = tokens[i].Split('=');
            string key = pair.Last();
            string value = null;
            string nextToken = tokens.ElementAtOrDefault(i + 1);
            if (nextToken != null)
            { 
                pair = nextToken.Split('=');
                value = pair.Last();
            }
            var keyVal = new KeyValuePair<string, string>(key, value);
            lineValues.Add(keyVal);
        }
        return lineValues;
    });

File.WriteAllLines(pathOutputFile, keyValuePairLines.SelectMany(l => 
    l.Select(kv=>string.Format("{0} = {1}", kv.Key, kv.Value))));

使用單個示例行在文件中輸出:

Speed = Fast
Fabricator = Freescale

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM