繁体   English   中英

使用Java脚本将数据与文本文件分开

[英]Separate data from text file using Javascript

我正在创建一个使用存储在文本文件中的数据的分析页面。 文本文件用于我的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并在某个位置进行计数?

您可以使用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. } 

暂无
暂无

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

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