Plotly.js - 파일 업로드하여 테이블 만들어보기

이번 Plot 자바스크립트는 txt 파일 업로드 시 단어의 빈도 수를 출력하도록 한다.
Plotly.js 라이브러리와 자바스크립트로 아래 코드로 삽입하여 작성되었다.

<input type="file" id="txtFile" accept=".txt">
<div id="table"></div>

<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<script>
const fileInput = document.getElementById('txtFile');

fileInput.addEventListener('change', function(event) {
  const file = event.target.files[0];
  if (!file) return;

  const reader = new FileReader();
  reader.onload = function(e) {
    const text = e.target.result;

    // 단어 전처리
    const words = text
      .toLowerCase()
      .replace(/[^a-z0-9가-힣\s]/g, '')  // 특수문자 제거
      .split(/\s+/)
      .filter(w => w.length > 0);

    // 빈도 계산
    const freq = {};
    words.forEach(w => {
      freq[w] = (freq[w] || 0) + 1;
    });

    // TXT 형태 배열로 변환
    const headerValues = ["단어", "빈도수"];
    const wordList = Object.entries(freq).sort((a, b) => b[1] - a[1]);
    const cellValues = [
      wordList.map(row => row[0]), // 단어
      wordList.map(row => row[1])  // 빈도
    ];

    // Plotly.js 테이블 (새로고침/덮어쓰기)
    var data = [{
      type: 'table',
      header: {
        values: headerValues,
        align: "center",
        line: {width: 1, color: 'black'},
        fill: {color: 'lightblue'},
        font: {family: "Arial", size: 12, color: "black"}
      },
      cells: {
        values: cellValues,
        align: "center",
        line: {color: "black", width: 1},
        fill: {color: ['white', 'lightgrey']},
        font: {family: "Arial", size: 11, color: "black"}
      }
    }];

    Plotly.newPlot('table', data);

    // 동일한 파일을 다시 선택해도 change 이벤트 발생하도록 초기화
    fileInput.value = "";
  };

  reader.readAsText(file);
});
</script>

파일업로드 하여 동작되는지 아래에서 확인해보자.