1
如何打印CSV文件中每個字段的最大長度?使用groovy計算csv文件中每個字段的最大長度
示例輸入:
foo,bar
abcd,12345
def,234567
預期輸出:
Max length of fields: [4, 6]
如何打印CSV文件中每個字段的最大長度?使用groovy計算csv文件中每個字段的最大長度
示例輸入:
foo,bar
abcd,12345
def,234567
預期輸出:
Max length of fields: [4, 6]
下面的代碼段將完成這項工作:
def txt='''foo,bar
abcd,12345
def,234567'''
txt.split('\n').collect { it.split(',') }.transpose().collect { field -> field.max { it.size() } }*.size()
最後,我用這個:
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}"
你可以使用'splitEachLine'而不是'eachLine'和後來的'split' – cfrick