简体   繁体   English

打开txt文件,取x,y值并用它们做图

[英]Open txt file, take x,y values and do graph with them

I have to open file and draw a graph with values from this file.我必须打开文件并使用该文件中的值绘制图形。 I only manage to open file with openfiledialog(), choose file and show valaues in richtextbox.我只能使用 openfiledialog() 打开文件,选择文件并在 Richtextbox 中显示值。 I am not sure how to separete xy values.我不确定如何分离 xy 值。

我有两个文件要使用,可能有随机数量的值,它们看起来像这样:

What is the best way to seperate x,y and plot graph?分离 x、y 和绘图的最佳方法是什么?

It depends what library for drawing plots expects.这取决于绘图图所需的库。 But if you need to replace spaces with some other separator, you can do this但是如果你需要用其他一些分隔符替换空格,你可以这样做

listOfValues = File.ReadAllLines("pathToFile.extension");
var formattedValues = new List<string>(listOfValues.Count);
listOfValues.ForEach(x => 
{
   formattedValues.Add(x.Replace(' ', yourCustomStringSeparator))
}

Here's a quick way to get an IEnumerable<(double x, double y)> containing your coordinates, where filename.txt is the name of the file containing your data:这是获取包含坐标的IEnumerable<(double x, double y)>的快速方法,其中filename.txt是包含数据的文件的名称:

var coordinates = File.ReadAllLines("filename.txt")
       .Select(line => line.Split(' '))
       .Select(line => (x: double.Parse(line[0]), y: double.Parse(line[1])));

Note that this doesn't account for parsing errors, empty lines, etc. You'd want to make this more robust for "production quality" code.请注意,这不考虑解析错误、空行等。您希望使其对“生产质量”代码更加健壮。

From here, you'll be somewhat dependent on what your charting library expects.从这里开始,您将在某种程度上依赖于您的图表库所期望的内容。 This SO answer might be helpful for some more information, although it's a few years old and may no longer be relevant.这个 SO 答案可能有助于提供更多信息,尽管它已经有几年的历史并且可能不再相关。

String.Split() and Double.Parse() to the rescue: String.Split()Double.Parse()来救援:

// Prepare some sample data
string sample="34.200250 85.0\r\n34.0202750 97.0";
// Get a culture that matches the input format
CultureInfo usCulture = new CultureInfo("en-US");
NumberFormatInfo decimalDotFormat = usCulture.NumberFormat;
// Split the whole data to get individual lines
foreach(string line in sample.Split(new[]{"\r","\n"}, StringSplitOptions.RemoveEmptyEntries))
{
   // Split the line again to get X and Y
   var values = line.Split(new[]{" "}, StringSplitOptions.RemoveEmptyEntries);
   double x = double.Parse(values[0], decimalDotFormat);
   double y = double.Parse(values[1], decimalDotFormat);
   // draw using x and y
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM