【问题标题】:Reading single data and arrays from the same text file从同一个文本文件中读取单个数据和数组
【发布时间】:2020-12-01 17:07:05
【问题描述】:

尝试读取 .txt 文件,其中包含大小和类型不同的问题数据(即单整数、双精度/整数/二进制数组)以进行计算实验。通过查看可用的示例herehere,我开发了两个替代代码块,但由于某种原因(我猜 Trim 方法不起作用)它们不起作用。它给出了“输入字符串格式不正确”的错误。有谁让我知道我做错了什么或错过了什么?

using System;
using System.IO;
namespace Program
{
   class Program
{
    // Basic parameters
    private static int x, y, z;
    private static double[,] array= new double[x, x];

    static void Main(string[] args)
    {
        string fileName = "LUU1_5.txt";
        ReadFile(fileName);            
    }

    static void ReadFile(string sourcefile) 
    {
        using (TextReader reader = File.OpenText(sourcefile)) 
        {
            // Method-1 Read line by line
            //x= int.Parse(reader.ReadLine());
            //y= int.Parse(reader.ReadLine());
            //z= int.Parse(reader.ReadLine());
            //int k=0;

            //for (int row2 = 3; row2 < 3 + 1 + x; row2++)
            //{
            //    k = 0;
            //    foreach (var row2 in reader.ReadLine()) 
            //    {
            //        foreach (var col in row2)
            //        {
            //            Console.WriteLine(col.Trim());
            //            //array[row2 - 3, k] = double.Parse(col.Trim());                //            
            //            k++;
            //        }
            //    }                       
            //}

            // Method 2-Read All Lines
            String[] content = File.ReadAllLines(sourcefile);                

            x= int.Parse(content[0]);
            y= int.Parse(content[1]);
            z= int.Parse(content[2]);

            int j = 0;
            for (int row = 3; row < 3 + 1 + x; row++)
            {
                j = 0;
                foreach (var col in content[row].Trim().Split(" "))
                {
                    Console.WriteLine(content[row]);
                    Console.WriteLine(col);
                    Console.WriteLine(col.Trim());   // using console for monitoring the output
                    Console.WriteLine(content[row].Trim().Split(" "));
                    array[row - 3, j] = double.Parse(col.Trim());
                    //array[row-3, j] = double.TryParse(col.Trim(), out array[row-3, j]);
                    j++;
                }
            } 
            // Then the program reads the next 0-1 array starting line 10.                               
            reader.Close();                 
        }
    }
 }
 }

数据文件如下所示:

5
2
100000
0   46.1    33.53   48.37   44.82   47.8
46.1    0   15.65   21.38   42.05   85.48
33.53   15.65   0   17.2    45.18   77.62
48.37   21.38   17.2    0   60.64   94.26
44.82   42.05   45.18   60.64   0   57.08
47.8    85.48   77.62   94.26   57.08   0
0   1   0   0   0   0
0   0   1   1   1   1
0   0   0   1   1   1
0   0   0   0   1   1
0   0   0   0   0   1
0   0   0   0   0   0

另外,我将在本实验的稍后部分为 array-x 读取更大的数据文件,例如 500x500 或 1000x1000,您认为我有任何速度或内存问题吗?我应该使用哪种方法(逐行或所有行合二为一)?我现在想相应地设计读取块。

提前致谢!

【问题讨论】:

  • 你有更多的列之间的空间,可能有标签。尝试以下操作: content[row].Trim()..Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
  • @jdweng,感谢您指出数据文件中空格和制表符的区别。没有注意到这一点。您的建议奏效了,我还用空格替换了制表符。

标签: c# arrays 2d read-text


【解决方案1】:

我认为使用 DTO 和正则表达式会更好。

public sealed class RowData
{
    public RowData(int number, int size = 5)
    {
        Number = number;
        Items = new List<float>(size);
    }

    public int Number { get; private set; }
    public List<float> Items { get; set; }

    public override string ToString()
    {
        return $"{Number}:{string.Join(" ",Items)}";
    }
}

static void ReadFile(string fileName)
{
    var regex = new Regex("[\\d\\.]+");
    var list = new List<RowData>();
    using (var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
    {
        using (var sr = new StreamReader(stream, Encoding.UTF8))
        {
            string line;
            var number = 0;
            int x =0;
            int y = 0;
            int z = 0; 
            while ((line = sr.ReadLine()) != null)
            {
                switch (number)
                {
                    case 0:
                        x = int.Parse(line);
                        break;
                    case 1:
                        y = int.Parse(line);
                        break;
                    case 2:
                        z = int.Parse(line);
                        break;
                    default:
                        var rowData = new RowData(number - 3);
                        var matches = regex.Matches(line);
                        foreach (Match match in matches)
                        {
                            var value = match.Value;
                            if (CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator != ".")
                                value = value.Replace(".", CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);
                            rowData.Items.Add(float.Parse(value));
                        }

                        list.Add(rowData);
                                break;

                }

                number++;

                
            }
        }
    }
    foreach (var rowData in list)
    {
        Console.WriteLine(rowData.ToString());
    }
}

【讨论】:

    猜你喜欢
    • 2015-08-05
    • 2015-11-08
    • 2015-08-11
    • 1970-01-01
    • 1970-01-01
    • 2014-11-07
    • 2021-04-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多