【问题标题】:write the results of for loop to csv in groovy在groovy中将for循环的结果写入csv
【发布时间】:2018-08-23 22:03:09
【问题描述】:

目前,我正在使用 Groovy 创建嵌套的 for 循环,将对象的内容打印到旨在成为分隔数据行的字符串。我想将这些字符串输出到 csv 文件,而不是打印出来。

代码如下:

for (doc in docs) {
    AnnotationSet row = doc.getAnnotations("Final").get("Row")
    AnnotationSet BondCounsel = doc.getAnnotations("Final").get("Bond_Counsel")
    AnnotationSet PurchasePrice = doc.getAnnotations("Final").get("PurchasePrice")
    AnnotationSet DiscountRate = doc.getAnnotations("Final").get("DiscountRate")
    for (b in BondCounsel) {
        for (d in DiscountRate) {
            for (r in row) {
                for (p in PurchasePrice) {
    println(doc.getFeatures().get("gate.SourceURL") + "|"
    + "mat_amount|" + r.getFeatures().get("MatAmount") + "|"
    + "orig_price|" + p.getFeatures().get("VAL") + "|"
    + "orig_yield|" + r.getFeatures().get("Yield") + "|"
    + "orig_discount_rate|" + d.getFeatures().get("rate")+ "|"
    + "CUSIP|" + r.getFeatures().get("CUSIPVAL1") + r.getFeatures().get("CUSIPVAL2") + r.getFeatures().get("CUSIPVAL3") + "|"
    + "Bond_Counsel|" + b.getFeatures().get("value"))
                }
            }
        }
    }
}

其中输出只是一系列字符串,例如:

filename1|mat_amt|3|orig_price|$230,000.....
filename2|mat_amt|4|orig_price|$380,000.....

我知道我可以设置一个文件写入器,即

fileWriter = new FileWriter(fileName);
csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);
csvFilePrinter.printRecord(FILE_HEADER);

<for loop here storing results>
csvFilePrinter.printRecord(forLoopResults)

但我不确定如何正确格式化和存储我当前在 for 循环中打印的内容,以便能够传递给 csvFilePrinter.printRecord()

任何帮助都会很棒。

【问题讨论】:

    标签: java groovy gate


    【解决方案1】:

    printRecord() 方法采用 Iterable(根据 doc)。例如一个列表。

    因此,在代码的内部循环中,我们将为该行创建一个列表,而不是打印。

    具体来说,鉴于此设置:

    def FILE_HEADER = ['Bond','Discount','Row','Price']    
    def fileName = 'out.csv'
    

    还有这个数据聚合(例如):

    def BondCounsel = ['bc1','bc2']
    def DiscountRate = ['0.1','0.2']
    def row = ['r1','r2']
    def PurchasePrice = ['p1','p2']
    

    然后这个(编辑:现在制作了 Groovier):

    new File(fileName).withWriter { fileWriter ->
        def csvFilePrinter = new CSVPrinter(fileWriter, CSVFormat.DEFAULT)
        csvFilePrinter.printRecord(FILE_HEADER)
    
        BondCounsel.each { b ->
            DiscountRate.each { d ->
                row.each { r ->
                    PurchasePrice.each { p ->
                        csvFilePrinter.printRecord([b, d, r, p])
                    }
                }
            }
        }
    }
    

    会生成这个到out.csv:

    Bond,Discount,Row,Price
    bc1,0.1,r1,p1
    bc1,0.1,r1,p2
    bc1,0.1,r2,p1
    ... etc
    

    【讨论】:

    • 嗨迈克尔 - 非常感谢这个和解释
    • 你不觉得rows这个变量是不必要的吗?我会直接打印该行:csvFilePrinter.printRecord([b, d, r, p])
    • @dedek 公平点。我已经更新了答案,使其更时髦。
    猜你喜欢
    • 2016-08-29
    • 2016-09-30
    • 1970-01-01
    • 1970-01-01
    • 2015-08-12
    • 2019-07-20
    • 2014-10-30
    • 2018-01-19
    • 2013-08-28
    相关资源
    最近更新 更多