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

时间:2016-04-03 08:34:53

标签: javascript html arrays text-files

我正在创建一个使用存储在文本文件中的数据的分析页面。文本文件用于我的highcharts图,并按如下方式分隔:

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并且在某处确定?

2 个答案:

答案 0 :(得分:0)

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 :(得分:0)

你需要

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

    &#13;
    &#13;
    // 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.
    }
    &#13;
    &#13;
    &#13;