我的StreamReader仅从我的4行文本文件中读取第二行和第四行

时间:2019-10-18 12:53:50

标签: c# text-files streamreader

我有一个程序,该程序从文件中读取数据,并使用该数据为图形创建节点。问题是,从4行文件中,我的程序仅创建两个节点(一行应创建一个节点)。文本文件如下所示:

A/0/0.7
C/1/0/0.1 0.4
B/1/0/0.6 0.8
D/2/2 1/0.6 0.7 0.1 0.2

Node数据的结构(它是贝叶斯网络):

节点名称/父级数目/文件中的父级索引/概率

using (StreamReader reader = new StreamReader(file))
            {
                while ((line = reader.ReadLine()) != null)
                {
                    line = reader.ReadLine();
                    string name = "";
                    List<int> parents = new List<int>();
                    List<float> probs = new List<float>();
                    string[] splitLine = line.Split('/');
                    Console.WriteLine("splitLine array: ");
                    foreach (string item in splitLine)
                    {
                        Console.WriteLine(item);
                    }
                    Console.WriteLine();
                    int index = 2;

                    name = splitLine[0];

                    if (splitLine.Length == 4)
                    {
                        string[] temp = splitLine[2].Split(' ');
                        foreach (string item in temp)
                            parents.Add(Int32.Parse(item));
                        index = 3;
                    }

                    string[] temp1 = splitLine[index].Split(' ');
                    foreach (string item in temp1)
                        probs.Add(float.Parse(item, CultureInfo.InvariantCulture.NumberFormat));

                    Node newNode = new Node(name, parents, probs);
                    graph.Add(newNode);
                }
            }

如果调用Node构造函数,程序将打印新节点具有的数据。我希望它能打印:

Created Node:
   Name: A
   Parents' indexes: 0
   Probabilities: 0.7
Created Node:
   Name: C
   Parents' indexes: 0
   Probabilities: 0.1 0.4
Created Node:
   Name: B
   Parents' indexes: 0
   Probabilities: 0.6 0.8
Created Node:
   Name: D
   Parents' indexes: 2 1
   Probabilities: 0.6 0.7 0.1 0.2

但是我得到:

Created Node:
   Name: C
   Parents' indexes: 0
   Probabilities: 0.1 0.4
Created Node:
   Name: D
   Parents' indexes: 2 1
   Probabilities: 0.6 0.7 0.1 0.2

3 个答案:

答案 0 :(得分:2)

您读了两行。

using (StreamReader reader = new StreamReader(file))
{
    while ((line = reader.ReadLine()) != null) // HERE
    {
        line = reader.ReadLine(); // AND HERE
        string name = "";
        List<int> parents = new List<int>();
        List<float> probs = new List<float>();
        string[] splitLine = line.Split('/');
        Console.WriteLine("splitLine array: ");
        foreach (string item in splitLine)
        {
            Console.WriteLine(item);
        }
        Console.WriteLine();
        int index = 2;

        name = splitLine[0];

        if (splitLine.Length == 4)
        {
            string[] temp = splitLine[2].Split(' ');
            foreach (string item in temp)
            parents.Add(Int32.Parse(item));
            index = 3;
        }

        string[] temp1 = splitLine[index].Split(' ');
        foreach (string item in temp1)
            probs.Add(float.Parse(item, CultureInfo.InvariantCulture.NumberFormat));

            Node newNode = new Node(name, parents, probs);
            graph.Add(newNode);
    }
}

如果您删除第二个读数,它应该可以工作。

答案 1 :(得分:2)

您两次致电reader.ReadLine()

while ((line = reader.ReadLine()) != null) // <-- First here
{
    line = reader.ReadLine(); // <-- Again here

只需删除第二个line = reader.ReadLine(),您的代码就是:

...
while ((line = reader.ReadLine()) != null)
{
    string name = "";
    List<int> parents = new List<int>();
...

答案 2 :(得分:0)

当其他人指出您的错误出在哪里时,我提出了一种新方法。

代码

using System.Linq;
(...)

const string input = @"A/0/0.7
C/1/0/0.1 0.4
B/1/0/0.6 0.8
D/2/2 1/0.6 0.7 0.1 0.2"; 


static void Main(string[] args)
{
  // Write to file to imitate the scenario
  System.IO.File.WriteAllText("x.txt", input);

  var lines = System.IO.File.ReadAllLines("x.txt");

  var parsed = lines.Select( l => {
    var components = l.Split("/");

    var hasExtra = components.Length > 3;
    return new { 
      Name = components[0],
      // Omit StringSplitOptions.RemoveEmptyEntries for brevity
      Parents = components[hasExtra ? 2 : 1].Split(" ").Select(s => int.Parse(s)).ToArray(),
      Probabilities = components[hasExtra ? 3 : 2].Split(" ").Select(s => decimal.Parse(s)).ToArray() 
    };
    }).ToList(); // Execute the 'Select'

  var json = System.Text.Json.JsonSerializer.Serialize(
      value: parsed, 
      options: new System.Text.Json.JsonSerializerOptions() { WriteIndented = true });

  Console.WriteLine(json);
}

输出

[
  {
    "Name": "A",
    "Parents": [
      0
    ],
    "Probabilities": [
      0.7
    ]
  },
  {
    "Name": "C",
    "Parents": [
      0
    ],
    "Probabilities": [
      0.1,
      0.4
    ]
  },
  {
    "Name": "B",
    "Parents": [
      0
    ],
    "Probabilities": [
      0.6,
      0.8
    ]
  },
  {
    "Name": "D",
    "Parents": [
      2,
      1
    ],
    "Probabilities": [
      0.6,
      0.7,
      0.1,
      0.2
    ]
  }
]