在javascript中从CSV计算值

时间:2017-11-09 13:21:28

标签: javascript json csv

如何在javascript中将CSV中的不同值计算为新的CSV或JSON?

像这样.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

到这一个:

API1,3
API2,2
API3,1

我在python中这样做但是我现在需要它在JS中:

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)

1 个答案:

答案 0 :(得分:0)

如果您将文件读入字符串数组,如:

Starting job test at 14:30 09/11/2017.

[statistics] connecting to socket on port 3854
[statistics] connected
.-----+-----+---+-----.
|     tLogRow_12      |
|=----+-----+---+----=|
|empno|ename|sal|grade|
|=----+-----+---+----=|
|101  |abc  |110|a    |
|102  |def  |250|b    |
|103  |fgh  |330|c    |
|104  |fff  |220|b    |
|105  |rrr  |190|a    |
'-----+-----+---+-----'

[statistics] disconnected
Job test ended at 14:30 09/11/2017. [exit code=0]

您可以编写一个函数来格式化它:

[
  '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'
]

并称之为......

function formatData(data) {
  var formattedData = [];

  data.map(
    (str) => {
      var formattedString = str.split(';')[1] + ',' + data.filter((d) => d.split(';')[1] === str.split(';')[1]).length;
      if (formattedData.indexOf(formattedString) === -1)
        formattedData.push(formattedString);
    }
  );

  return formattedData;
}

它会返回

formatData(d);