簡體   English   中英

如何在nodejs中從CSV文件列中讀取數據

[英]How to read Data from CSV file column wise in nodejs

我有一個 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

        }) 

我最后想要的是有一個 arrays 數組,其中包含單獨的 arr 中的每列數據,(例如; Arr = [ [col1 data(6 rows)], [col2 data(3 rows)] ]

我真正的 csv 文件有一個類似 10000 的列,將來它可能會更大。

在下面查看我對您的問題的處理方法。

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);
  });

這是另一種方法,它只在最后進行必要的轉換,而前一種方法是在每一行上進行轉換。

盡管這兩種解決方案都應該有效,但我會做一些基准測試並選擇性能更好的一種。

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
    }, [ [], [] ])
    
  });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM