使用javascript读取csv-txt文件并将结果加载到数组中

Using javascript to read a csv txt file and load results into an array

本文关键字:加载 结果 数组 javascript 读取 csv-txt 文件 使用      更新时间:2023-09-26

我正试图使用javascript读取一个CSV格式的txt文件,对其进行解析并将其加载到一个数组中,这样我就可以对其进行数学运算(求和、平均、标准差(。我已经阅读了文本文件,我需要帮助解析它

谢谢!

inputExample.txt

5,4,4,4,4
3,3,3,3,2
1,5,4,7,6

index.html

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <input type="file" id="openFile" />
    <br>
    <pre id="fileContents"></pre>
    <script type="text/javascript" src="app.js"></script>
</body>
</html>

app.js

document.getElementById("openFile").addEventListener('change', function(){
    var fr = new FileReader();
    fr.onload = function(){
        // document.getElementById("fileContents").textContent = this.result;
        console.log(this.result);

    }
    fr.readAsText(this.files[0]);
})
var arr = this.result.split(',');

如果您的内容也用新行分隔,例如,您可以用逗号替换它们,然后将它们拆分。

var arr = this.result.replace(/'n/g, ',').split(',');

这是一个很常见的问题。可以使用正则表达式或字符串运算。

这个使用正则表达式:

 // I am assuming your file has newline and carriage return, depending on your file format, it may have either of them or both of them
 var foo = "5,4,4,4,4'n'r3,3,3,3,2'n'r1,5,4,7,6";
 var regex = /('d)(?=,|'n'r?)?/g;
 var arr = foo.match(regex);
 console.log(arr); //[ '5', '4', '4', '4', '4', '3', '3', '3', '3', '2', '1', '5', '4', '7' ]

这个使用字符串操作:

 var foo = "5,4,4,4,4'n'r3,3,3,3,2'n'r1,5,4,7,6";
 var arr = [];
 foo = foo.split(''n'r').forEach(function(el){
     el = el.split(',').forEach(x => arr.push(x));
 });
 console.log(arr); //[ '5', '4', '4', '4', '4', '3', '3', '3', '3', '2', '1', '5', '4', '7', '6' ]

请查看有关如何详细解析csv的链接。

如何使用Javascript解析数据中包含逗号的CSV字符串?