我只想删除多余的逗号,但不想移动任何数据。只要去掉多余的逗号,让单元格为空。
| 一种|B| c型|d| e的|关闭|
| - -----|- -----|- -----|- -----|- -----|- -----|
| 第一排|1| 0|、|、|、|
| 第二排|1| 1| 3|、|、|
| 第三排|1|、|3|、|、|
我想要=
| 一种|B| c型|d| e的|关闭|
| - -----|- -----|- -----|- -----|- -----|- -----|
| 第一排|1| 0||||
| 第二排|1| 1| 3|||
| 第三排|1||3|||
我写了下面的代码,多余的逗号被删除,但数据被转移到前一列:
const fs = require('fs');
const readline = require('readline');
// Function to remove extra commas from a line
function removeExtraCommas(line) {
let withinQuotes = false;
let result = '';
for (let i = 0; i < line.length; i++) {
const char = line[i];
if (char === '"') {
withinQuotes = !withinQuotes;
result += char;
} else if (char === ',' && withinQuotes) {
result += char;
} else if (char === ',' && !withinQuotes) {
const nextChar = line[i + 1];
if (nextChar === ',') {
result += '';
} else {
result += char;
}
} else {
result += char;
}
}
return result;
}
// Function to process the CSV file
function processCSVFile(filePath) {
const outputFilePath = '../70_primary_codesData2CSV/70 Primary Codes Data/19120/19120(828+828_new)withoutExtraS.csv';
const fileStream = fs.createReadStream(filePath);
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity
});
const outputStream = fs.createWriteStream(outputFilePath);
rl.on('line', (line) => {
const processedLine = removeExtraCommas(line);
outputStream.write(processedLine + '\n');
});
rl.on('close', () => {
console.log('CSV file processed successfully.');
});
}
// Example usage
const filePath = '../70_primary_codesData2CSV/70 Primary Codes Data/19120/19120(828+828_new).csv'; // Replace with your input file path
processCSVFile(filePath);
2条答案
按热度按时间dkqlctbz1#
试试这个:
你会被一个空间取代
r55awzrz2#
当
removeExtraCommas
函数遇到一个额外的逗号时,它会将一个空的string
''附加到结果中,因此数据会转移到前一列。要求应该是在结果中附加一个空的
value
,以确保列保持对齐。解决方案是引入一个列变量来跟踪当前列值。
请参见下面更新的
removeExtraCommas
函数,这应该可以解决数据移位问题: