使用d3.dsv.parseRows读取格式化数据

时间:2013-09-16 13:15:12

标签: javascript d3.js formatting

我开始学习javascript和d3.js(版本3.3.3)。我需要从文件中读取数据,格式既不是csv也不是tsv。我可以使用d3.dsv.parseRows,但我有点坚持 - 我真的很感激一些帮助才能开始,一个例子会很棒。

数据格式为ASCII,两列数字由未知数量的空白字符(制表符或空格)分隔。评论字符为#

# Example 
# The data is obviously poorly aligned
# The two values in each row are separated 
# by one or more tabs and/or spaces
#
1.0   10.00
  2.0    20
3.0     30.          # this data line should be read
#  4.0    40.0       # this data line should be ignored
5.0   50.00

我需要将数据放在数组数组中,所以我可以继续使用一些不错的d3绘图:

[ [1.0,10.0], [2.0,20.0], [3.0,30.0], [5.0,50.0] ]

2 个答案:

答案 0 :(得分:0)

听起来你必须写下你自己的要求,我已经在下面有几个笔记开始,你需要完成它虽然...

var dsvFile = new XMLHttpRequest();
    dsvFile.open("GET", "dsv.txt", true);

var req = new XMLHttpRequest();
    req.onreadystatechange = function () {
      if (req.readyState == 4) {
        if (req.status === 200 || 
            req.status === 0) {

            var data = req.responseText;
            cleanData(data)
          }
        }
      };

    req.open('GET', "dsv.txt", true);
    req.send(null);

    var cleanData = function(data) {

      var clean = [];
      var lines = data.split("\n");

      for (var i = 0; i < lines.length; i++) {
        var comment = /^#/
        var whiteSpace = /^\s+/
        var OK = comment.exec(lines[i]) // check for comment lines
        var white = whiteSpace.exec(lines[i]) // check white whitespace at begining of line
        if(!OK) // if no comments then
          { 
            if(white) // if whitespace at begining of line remove 
            {
              var str = lines[i].replace(whiteSpace, '')
            } 
            else 
            {
              var str = lines[i]
            }
          clean.push(str)
          }
      };

      console.log(clean)

    };

答案 1 :(得分:0)

要处理具有多个空格(可能还有更复杂的模式)的数据文件, d3.text 可以与正则表达式结合,然后 d3.csvParseRows

var a = [];
d3.text("http://cdsarc.u-strasbg.fr/ftp/J/AJ/159/187/table3.dat")
     .then(function(d){a = d3.csvParseRows(d.replace(/ +/g, ","))})

请注意,由于 CORS,网址仅适用于某些网页。