如何在CSV文件中打印出每个字段的最大长度?
示例输入:
foo,bar
abcd,12345
def,234567
预期产出:
Max length of fields: [4, 6]
答案 0 :(得分:1)
以下代码将完成这项工作:
def txt='''foo,bar
abcd,12345
def,234567'''
txt.split('\n').collect { it.split(',') }.transpose().collect { field -> field.max { it.size() } }*.size()
答案 1 :(得分:0)
最后,我使用了这个:
def csv = new File('./myfile.csv').text
def max = [ ] as ArrayList
csv.eachLine { line, count ->
def params = line.split(',')
// skip the header line
if (count > 0)
{
params.eachWithIndex() { p, index ->
if (p.length() > max[index] ) {
max[index] = p.length()
}
}
}
}
println "Max length of fields: ${max}"