簡體   English   中英

從.txt文件導入x和y坐標

[英]Import x and y coordinates from .txt file

我需要從文本文件中讀取項目的坐標,但是文本文件是這樣的

1 37.4393516691 541.2090699418

2 612.1759508571 494.3166877396

3 38.1312338227 353.1484581781

並且前面有更多空間。我嘗試了一些代碼,但無法使分隔符正常工作。

      1    1150.0  1760.0

      2     630.0  1660.0

      3      40.0  2090.0

編碼:

 string[] cityPositions = File.ReadAllLines(ofd.FileName);
                foreach (string cityP in cityPositions)
                {
                    int startIndexX = cityP.IndexOf("  ", StringComparison.CurrentCultureIgnoreCase) + 3;
                    int endIndexX = cityP.IndexOf(" ", StringComparison.CurrentCultureIgnoreCase);
                    int X = int.Parse(cityP.Substring(startIndexX, endIndexX - startIndexX));

                    int startIndexY = cityP.IndexOf(" ", StringComparison.CurrentCultureIgnoreCase) + 3;
                    int endIndexY = cityP.IndexOf("", StringComparison.CurrentCultureIgnoreCase);
                    int Y = int.Parse(cityP.Substring(startIndexY, endIndexY - startIndexY));
                    create_City(new Point(X, Y));
                }

首先,您的數據類型不匹配。 您應將double用作坐標,並使用Split方法,例如:

double X = double.Parse(cityP.Split()[1], CultureInfo.InvariantCulture);
double Y = double.Parse(cityP.Split()[2], CultureInfo.InvariantCulture);

沒有給出參數的分割函數將被空格分割。

編輯

問題尚不清楚,但是,如果您的行沒有相同的模式,並且空格不同,請使用Split方法,如下所示:

double X = double.Parse(cityP.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)[1], CultureInfo.InvariantCulture);

如果要使用正則表達式,請嘗試以下操作:

        String expression = @"(\d)([\d\.]*)([\d\.]*)";

        Regex r = new Regex(expression);

        foreach (String cityPosition in cityPositions)
        {
            MatchCollection mc = r.Matches(cityPosition);
            int index = Convert.ToInt32(mc[0].Value);
            decimal coOrdX = Convert.ToDecimal(mc[1].Value);
            decimal coOrdY = Convert.ToDecimal(mc[2].Value);

            Console.WriteLine(String.Format("{0} {1} {2}", index, coOrdX, coOrdY));
        }

此代碼將產生以下輸出:

1 1150.0 1760.0
2 630.0 1660.0
3 40.0 2090.0

它應該忽略這些值之間變化的空間量,並使解析文件中的三個不同值變得更加容易。

除了使用索引,您還可以用一個空格替換多個空格,例如

    RegexOptions options = RegexOptions.None;
    Regex regex = new Regex("[ ]{2,}", options);     
    cityP = regex.Replace(cityP, " ");

然后使用split獲取坐標

    var x = double.Parse(cityP.Split()[1]);
    var y = double.Parse(cityP.Split()[2]);

暫無
暫無

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

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