输入字符串格式不正确 字符串到双精度 [] [] 数组



我知道这里有更多关于这个主题的线程,但它们实际上都没有帮助我。

我将提供整个代码:

namespace ConsoleApplication1
{
    public static class Load
    {
        public static double[][] FromFile(string path)
        {
            var rows = new List<double[]>();
            foreach (var line in File.ReadAllLines(path))
            {
                // HERE IS THE ERROR
                rows.Add(line.Split(new[] { ' ' }).Select(double.Parse).ToArray());  
            }
            return rows.ToArray();
        }
    }
    public class Program
    {
        static void Main( string [ ] args )
        {
            string cestain = @"E:vstup.txt";
            double[][] innput = Load.FromFile(cestain);
            string cestaout = @"E:vystup.txt";
            double[][] ooutput = Load.FromFile(cestaout);

            // c r e a t e a neural network
            var network = new BasicNetwork ( ) ;
            network . AddLayer (new BasicLayer ( null , true , 2) ) ;
            network . AddLayer (new BasicLayer (new ActivationSigmoid ( ) , true , 3) ) ;
            network . AddLayer (new BasicLayer (new ActivationSigmoid ( ) , false , 1) ) ;
            network . Structure . FinalizeStructure ( ) ;
            network . Reset( );
            // c r e a t e t r a i n i n g data
            IMLDataSet trainingSet = new BasicMLDataSet (innput , ooutput ) ;
            // t r a i n the neural network
            IMLTrain train = new ResilientPropagation (network , trainingSet) ;
            int epoch = 1 ;
            do
            {
                train.Iteration( ) ;
                Console.WriteLine(@"Epoch #" + epoch + @" Error : " + train.Error );
                epoch++;
            } while ( train.Error> 0.01 ) ;
            Console.ReadLine();
        }
    }
}

这是我尝试加载到double[][]输入的内容:

166 163 180 228

165 162 160 226

166 163 180 228

166 164 180 228

171 162 111 225

这是我尝试加载到double[][]输出的内容:

1 0 0
1 0 0
0 1 0
0 1 0
1 0 0

问题:文本文件中的每一行之后都有额外的空行。当 Split() 函数遇到新行时,它会返回,因为它没有要拆分的内容Add()并且函数抛出异常,因为空行不是有效的Double

解决方案1:您可以使用StringSplitOptions.RemoveEmptyEntries作为第二个参数来Split()函数忽略空行。

        foreach (var line in File.ReadAllLines(path))
            {
                // HERE IS THE ERROR
                rows.Add(line.Split(new[] { ' ' },StringSplitOptions.RemoveEmptyEntries).Select(double.Parse).ToArray());  
            }

解决方案2:您可以使用String.IsNullOrWhiteSpace()检查该行是否为空

          foreach (var line in File.ReadAllLines(path))
            {
              if(!String.IsNullOrWhiteSpace(line))
              {
                // HERE IS THE ERROR
                rows.Add(line.Split(new[] { ' ' },StringSplitOptions.RemoveEmptyEntries).Select(double.Parse).ToArray());  
              }                
            }
<</div> div class="one_answers">不久

前我遇到了类似的问题。使用StringSplitOptions.RemoveEmptyEntries为我解决了它。事情就这样变成了,lines.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)

它很有帮助,因为您得到的是空行,因此RemoveEmptyEntries从 Split 方法的结果中删除这些行。

最新更新