gpt4 book ai didi

java - 读取 CSV 文件并使用 Grails/Groovy 将结果放入 map 中

转载 作者:行者123 更新时间:2023-11-29 04:49:55 25 4
gpt4 key购买 nike

我正在使用下面的代码读取一个 csv 文件,并希望将结果放入 map 中

def fileName = 'C:/temp/exampleCSV.csv'
def reader = new CSVReader(new FileReader(new File(fileName)))
def header = reader.readNext()
def rows = reader.readAll().collect { row ->
(0..(row.size()-1)).collectEntries { [header[it], row[it]] }
}

CSV:

name;cuInfo;service;startDate;appId
Apple;T12;3;14-02-16 10:00;G12351
Apple;T13;3;14-01-16 13:00;G12352
Google;T14;9;10-01-16 11:20;G12301
Microsoft;T15;10;26-02-16 10:20;G12999

但是上面的代码给出了输出:

  [
[name;cuInfo;service;startDate;appId:Apple;T12;3;14-02-16 10:00;G12351],
[name;cuInfo;service;startDate;appId:Apple;T13;3;14-01-16 13:00;G12352],
[name;cuInfo;service;startDate;appId:Google;T14;9;10-01-16 11:20;G12301],
[name;cuInfo;service;startDate;appId:Microsoft;T15;10;26-02-16 10:20;G12999]
]

我想得到如下图所示的结构吗?

[
[name:"Apple", cuInfo:"T12",service:"3",startDate:"14-01-16 13:22",appId:"G12355"],
[name:"Apple",cuInfo:"T13",service:"3",startDate:"12-02-16 13:00",appId:"G12356"],
[name:"Google",cuInfo:"T14",service:"9",startDate:"10-01-16 11:20",appId:"G12300"],
[name:"Microsoft",cuInfo:"T15",service:"10",startDate:"26-02-16 10:20",appId:"G12999"]
]

最佳答案

要将 CSV 文件中的数据转换为与查询输出相同的结构( map 列表),您可以这样做:

def reader = new CSVReader(new FileReader(new File(fileName)))
def output = reader.collect { it[0].split(';') }.with { rows ->
def header = rows.head()
def dataRows = rows.tail()

dataRows.collect { row ->
[header, row].transpose().collectEntries()
}
}

将 CSV 行拆分为列,收集标题和其余行,然后进行转换。

transpose() 为每个数据行创建这样的结构:

[[name, Apple], [cuInfo, T12], [service, 3], [startDate, 14-02-16 10:00], [appId, G12351]]

collectEntries() 将其转换为 Map:

[name:Apple, cuInfo:T12, service:3, startDate:14-02-16 10:00, appId:G12351]

关于java - 读取 CSV 文件并使用 Grails/Groovy 将结果放入 map 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35843130/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com