使用 groovy 计算 csv 文件中每个字段的最大长度
calculate max length of each field in csv file using groovy
如何打印出 CSV 文件中每个字段的最大长度?
示例输入:
foo,bar
abcd,12345
def,234567
预期输出:
Max length of fields: [4, 6]
最后我用了这个:
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}"
下面的一段代码可以完成这项工作:
def txt='''foo,bar
abcd,12345
def,234567'''
txt.split('\n').collect { it.split(',') }.transpose().collect { field -> field.max { it.size() } }*.size()
如何打印出 CSV 文件中每个字段的最大长度?
示例输入:
foo,bar
abcd,12345
def,234567
预期输出:
Max length of fields: [4, 6]
最后我用了这个:
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}"
下面的一段代码可以完成这项工作:
def txt='''foo,bar
abcd,12345
def,234567'''
txt.split('\n').collect { it.split(',') }.transpose().collect { field -> field.max { it.size() } }*.size()