来自javascript的CSV平均值

时间:2017-11-07 17:06:20

标签: javascript python csv

我有一个python脚本,用于在本地读取和写入csv。它还计算行数的平均值。现在我需要在JS native中翻译它。但我甚至没有成功地将它显示在阵列中。阵列保持空白,我不知道为什么。

我使用的CSV看起来像:

outbound;API1;Restitution;1.0
outbound;API1;Restitution;1.0
outbound;API1;Operations;1.0
outbound;API2;Operations;2.0
outbound;API2;Operations;2.0
outbound;API3;Service;1.0

当我用我的python脚本翻译它时,我获得了类似的东西:

API1,0.50
API2,0.33333
API3,0.16666

我要翻译的python脚本:

import csv
from glob import glob

myDict = {}
filename = glob('*.csv')[0]     #take any .csv file
row_number = 0

with open(filename, 'rU') as f:     #arg 'r' for reading and 'U' for Universal, can read .csv without quotes.
    reader = csv.reader(f, delimiter=';')
    for row in reader:
        row_number +=1
        if row[1] in myDict:
            myDict[row[1]] += 1
        else:
            myDict[row[1]] = 1

data = open("output.csv", "w")
w = csv.writer(data)
for word in myDict:
    data = word, float(myDict[word])/row_number*100
    w.writerow(data)

我的JS功能:

var a_api = new Array();
            $.get('/data/dataTest2.csv', function(data) {
              let rows = data.split("\n");
              rows.forEach( function getvalues(thisRow) {
                let columns = thisRow.split(";");
                for (var i=0;i<a_api.length;i++){
                  if(columns[1]==a_api[i]){
                    a_api[i][1] +=1;
                  }
                  else {
                    a_api[i][0]=columns[1];
                    a_api[i][1]=1;
                  }
                }
              })
               });
console.log(a_api);

0 个答案:

没有答案