亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

CSV-Parser 似乎無法正確解析換行數據

CSV-Parser 似乎無法正確解析換行數據

HUX布斯 2022-06-09 19:07:08
是的,我知道我應該有更好的數據,如果沒有任何效果,我會修復我的數據,但我想知道是否有任何方法可以讓 csv-parser 解析器解析"United States ofAmerica",140640,17987,2398,286,Local transmission,0進入{Country: United States of America... blah blah... blah blah... blah blah... blah blah}fs.createReadStream("./csv/03312020.csv")    .pipe(        csv([            "Country",            "Total",            "TotalNew"        ])    )    .on("data", row => {        console.log(row.Country);        let result = contains(row.Country);        if (result !== undefined) {            row.Date = today;            row.id = result + "-" + today;            if (db.dates.get(row.id) === undefined) db.dates.create(row);        }    })    .on("end", () => {        console.log("CSV file successfully processed for", today);    });我認為 csv-parser 會看到有一個引號并將其包裝為一個“列”,但顯然它沒有。除了重新解析我的 CSV 文件本身之外,還有更好的方法來解析這些數據嗎?
查看完整描述

1 回答

?
慕森王

TA貢獻1777條經驗 獲得超3個贊

您可以做的是將該文件拆分為行,然后加入具有奇數個 " 字符的行。


我的腳本還處理 \n 字符在單行數據中多次出現的情況。

這是基于這樣一個事實,即只有多行行的第一行和最后一行會有奇數個 " 字符。


您可以使用我的腳本重新格式化您的文件,然后將其輸入您的 csv 解析器。


const example1 = `"United States of

America",140640,17987,2398,286,Local transmission,0`;


console.log(reformatCsv(example1));


const example2 = `"United States of

America",140640,17987,2398,286,"Local

transmission",0`;


console.log(reformatCsv(example2));



// @param file: string

function reformatCsv(file)

{

    const lines = file.split('\n');


    let reformattedRows = [];


    const parts = [];


    for (const line of lines)

    {

        const quoteMatches = line.match(/"/g);

        const isEvenNumberOfQuotes = !quoteMatches || quoteMatches.length % 2 == 0;

        const noPartialRowsYet = !parts.length;


        if (noPartialRowsYet)

        {

            if (isEvenNumberOfQuotes) // normal row

            {

                reformattedRows.push(line);

            }

            else // this is a partial row

            {

                parts.push(line);

            }

        }

        else // continuation of a partial row

        {

            parts.push(line);

            if (!isEvenNumberOfQuotes) // we got all of the parts

            {

                // join the parts

                // I replace \n with a space character, but you don't have to

                reformattedRows.push(parts.join(' '));

            }

        }

    }


    return reformattedRows.join('\n');


查看完整回答
反對 回復 2022-06-09
  • 1 回答
  • 0 關注
  • 200 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號