2016-11-09 2 views
1

javascript를 사용하여 내용을 CSV 형식으로 된 txt 파일을 읽은 다음 구문 분석하고 단일 배열로로드 할 수 있도록 노력하고 있습니다. 수학 연산을 (합계, 평균, 표준 편차) 좋아하십시오. 지금까지 텍스트 파일을 읽었을 때 파싱에 대한 도움이 필요했습니다.자바 스크립트를 사용하여 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> 

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]); 
}) 
+1

가능한 중복 : http://stackoverflow.com/a/12289296/1743938 –

답변

2
var arr = this.result.split(','); 

을 app.js 당신 그 (것)들을 쉼표로 대체하고 그 후에 spl 그것들.

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

이것은 매우 일반적인 질문입니다. 정규 표현식이나 문자열 연산을 사용할 수 있습니다.

이 사람은 정규 표현식 사용

// 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를 구문 분석하는 방법에 대한이 링크를.

How can I parse a CSV string with Javascript, which contains comma in data?

관련 문제