使用Javascript将数据从文本文件中分离出来

Separate data from text file using Javascript

本文关键字:文件 分离出 文本 Javascript 数据 使用      更新时间:2023-12-17

我正在创建一个使用存储在文本文件中的数据的分析页面。文本文件用于我的高图,并且像这样分开:

November 7th 6AM,19.8
November 7th 6PM,19.8
November 8th 6AM,20.4
November 8th 6PM,14.6
November 9th 6AM,15.9
November 9th 6PM,15.1
November 10th 6AM,16.4
November 10th 6PM,16.4

我希望将这些数据分为12个日历窗格,这些窗格将显示每个月的总体差异。例如,如果一个日期的值为16,然后在下一次读数时下降到10,则计算该月发生的累计次数。

我如何确保它以正确的顺序从文本文件中读取,并检查下一个值是否低于10,并在某个地方进行计数?

Yo可以使用jQuery将文件数据分离到数组中。

$(document).ready(function() {
    //fetch text file
    $.get('text.txt', function(data) {
        //split on new lines
        var lines = data.split(''n');
        for(var i=0;i<lines.length;i++) {
            // use lines[i] the way you want
        }
    });
});

然后您可以使用它来获取子字符串:

var a = s.indexOf(',');
var b = s.substring(a,4);

通过这种方式,您可以分离数据并根据需要使用它。

您需要

  1. 获取数据文件
    • 通常使用AJAX(XMLHttpRequest)来执行此操作
  2. 分离数据点
    • 您的数据似乎足够整洁,可以为文件中的每一行获取带有line.split(" ")[0]的月份名称和带有line.split(",")[1]的值。将文本拆分为行通常可以像text.split("'n")一样简单
  3. 迭代结果
    • 对于您现在拥有的每个月值对,比较月份的名称。如果匹配,并且值已更改x,请在书本中增加一个值,例如discrepancies[monthName]++。保存名称-值对并继续

示例:

// Get the data
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
  if (req.readyState == 4 && req.status == 200) { // If the request is complete with status code "OK"
    handleImportantData(req.responseText);
  }
};
// Define the request to be using the method GET to an URL asynchronously.
req.open("GET", "important_data.txt", true);
req.send();
function handleImportantData(data) {
  var treshold = 5.0;
  var months = {};
  var discrepancies = {};
  // Separate data points.
  var lines = data.split("'n");
  lines.forEach(function(line) {
    // The || 0.0 part sets the value to zero if our data is malformed.
    // We parse the value as a float to prevent it being saved as a string,
    // which would make arithmetic operations on it not work as expected.
    months[line.split(" ")[0]] = parseFloat(line.split(",")[1]) || 0.0;
  });
  // Find discrepancies.
  var previous = {
    name: "",
    value: 0.0
  };
  for (var name in months) {
    // If not already there, initialize the data point with ternary operation including NOP.
    discrepancies[name] ? {} : discrepancies[name] = 0.0;
    // If we're still talking about the same month as before and the value
    // has changed for more than our treshold, save it as a discrepancy.
    if name === previous.name && Math.abs(previous.value - months[name]) > treshold {
      discrepancies[name] ++;
    }
    previous = {
      name: name,
      value: months[name]
    }; // Set this as the previous value.
  }
  // Here we have ready discrepancy data stored in the variable discrepancies.
}