【问题标题】:My StreamReader reads only second and fourth lines from my 4 line text file我的 StreamReader 只从我的 4 行文本文件中读取第二行和第四行
【发布时间】:2019-10-21 21:14:05
【问题描述】:

我有一个程序,它从文件中读取数据并使用该数据为图形创建节点。问题是,从一个 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);
                }
            }

如果调用节点构造函数,程序会打印新节点的数据。我希望它打印出来:

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

【问题讨论】:

    标签: c# text-files streamreader


    【解决方案1】:

    您拨打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】:

      你把这行读了两遍。

      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);
          }
      }
      

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

      【讨论】:

        【解决方案3】:

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

        代码

        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
            ]
          }
        ]
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-08-27
          • 2017-03-01
          • 1970-01-01
          相关资源
          最近更新 更多