当前,我正在使用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"))
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
输出只是一系列字符串,例如:
filename1|mat_amt|3|orig_price|$230,000.....
filename2|mat_amt|4|orig_price|$380,000.....
Run Code Online (Sandbox Code Playgroud)
我知道我可以设置文件编写器,即
fileWriter = new FileWriter(fileName);
csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);
csvFilePrinter.printRecord(FILE_HEADER);
<for loop here storing results>
csvFilePrinter.printRecord(forLoopResults)
Run Code Online (Sandbox Code Playgroud)
但是我不确定如何正确格式化和存储我正在for循环中打印的内容以传递给 csvFilePrinter.printRecord()
任何帮助都会很棒。
该printRecord()方法采用Iterable(每个文档)。例如清单。
因此,在代码的内部循环中,而不是打印,我们将为该行创建一个列表。
具体来说,鉴于此设置:
def FILE_HEADER = ['Bond','Discount','Row','Price']
def fileName = 'out.csv'
Run Code Online (Sandbox Code Playgroud)
和此数据聚合(例如):
def BondCounsel = ['bc1','bc2']
def DiscountRate = ['0.1','0.2']
def row = ['r1','r2']
def PurchasePrice = ['p1','p2']
Run Code Online (Sandbox Code Playgroud)
然后这个(编辑:现在制成Groovier):
new File(fileName).withWriter { fileWriter ->
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])
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
将生成此到out.csv:
Bond,Discount,Row,Price
bc1,0.1,r1,p1
bc1,0.1,r1,p2
bc1,0.1,r2,p1
... etc
Run Code Online (Sandbox Code Playgroud)