[英]Properly getting X and Y coordinates from a text file and plot the curve
[英]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.