【问题标题】:How to read Data from CSV file column wise in nodejs如何在nodejs中从CSV文件列中读取数据
【发布时间】:2020-06-23 12:19:07
【问题描述】:

我有一个 CSV 文件,列数(包含标题作为列 ID),每列下有一组行(包含每列的数据)但不是每列的行都相等(例如:col1,可以有 4 行.. 但 col2 可以有 8 行。)

我想要做什么我正在尝试读取每列的数据并将其保存在列表中以便稍后在某些处理中使用它。

我正在尝试使用 CSV 解析器,但我不知道如何仅访问特定列的数据。

这里是 csv 的示例

1 ,2
How do I change my password? ,Why we use bottels?
How can I change my password? ,Why you're lazy?
How do I reset my password? ,Why do I get the message that the name of my APK is in use?
How to do a password change?    
How do I do a password change?  
How can a password be changed?  

到目前为止,我一直在尝试这样做

fs.createReadStream('test.csv')
    .pipe(csv())
    .on('data', (row) => {
        //console.log('New row ',row);

        if (columns === null) {
            columns = [];
        
            Object.keys(row).forEach(function (c) {
                console.log(c) // this print headers only
                //columns.push(c);
            })
        
        }
        Object.entries(row).forEach((r)=>{
            console.log(r) // this prints the entire objects data

        }) 

我最后想要的是在一个单独的 arr 中包含一个包含每列数据的数组数组,(例如;Arr = [ [col1 data(6 rows)] , [col2 data(3 rows)] ]

我真正的 csv 文件有一个 10000 列,将来可能会更大。

【问题讨论】:

  • 您的实际 CSV 是这样的吗?句子之间应该有逗号...
  • 我只是发布一个列的外观示例。
  • 您应该发布实际的 CSV(其中的一部分),以便有人可以对您的代码进行一些测试。
  • @AlexMichailidis 首先感谢您的帮助。其次,据我所知,如果我想将任何数据写入 CSV 文件,我应该预先定义列并将数据发送到 stream.write() 中的这些列,但我想知道我是否可以让它动态创建列,就像任何时候一样在我的列表中创建了一个新列,它应该在 csv 中创建。 (我对 JS 有点陌生)(我想我应该为此提出一个问题:d ?)
  • 是的,我认为这个话题需要自己的问题

标签: javascript node.js csv


【解决方案1】:

在下面查看我解决问题的方法。

const csv = require('csv-parser')
const fs = require('fs')
const results = [];

fs.createReadStream('data.csv')
  .pipe(csv())
  .on('data', (data) => {
    /* data would be something like :
        { '2': 'Why we use bottels?', '1 ': 'How do I change my password? ' }
    */
    Object.entries(data)
      .forEach(([key, value]) => {
        // key would be the column number (1 or 2)
        // value would be the data of the row
        // we "abuse" the fact that the column happens to be a number between 1 and 2 and we use that as the array index
        let index = parseInt(key) - 1;
        results[index] = results[index] || []
        results[index].push(value)
      })
  })
  .on('end', () => {
    console.log(results);
  });

【讨论】:

    【解决方案2】:

    这是另一种方法,它只在最后进行必要的转换,与之前对每一行进行转换的方法不同。

    虽然这两种解决方案都应该有效,但我会做一些基准测试并选择性能更好的一种。

    const csv = require('csv-parser')
    const fs = require('fs')
    let results = [];
    
    fs.createReadStream('aou.csv')
      .pipe(csv({
        headers: false,
        skipLines: 1,
      }))
      .on('data', (data) => results.push(data)) // simply push the data in the results array
      .on('end', () => {
        // transform the results array into the desired format
        results = results.reduce((prev, curr) => {
          if (curr[0]) prev[0].push(curr[0])
          if (curr[1]) prev[1].push(curr[1])
          return prev
        }, [ [], [] ])
        
      });
    

    【讨论】:

      猜你喜欢
      • 2019-06-01
      • 2013-01-13
      • 2020-08-28
      • 1970-01-01
      • 1970-01-01
      • 2014-01-07
      • 2019-09-17
      相关资源
      最近更新 更多