Groovy GroupBy包含和不包含空格的字段

时间:2015-06-11 19:11:56

标签: collections groovy

我的发票清单如下

def invoices = [
'LEDES98BI V2',
'LINE|INVOICE_DATE|INVOICE_NUMBER|INVOICE_TOTAL',
'1|20150301|INV-Error_Test1|22',
'2|20150301|INV-Error_Test1|24',
'3|20150301|INV-Error_Test2|26',
'4|20150301|INV-Error_Test2|28,']

我正在尝试使用INVOICE_NUMBER对上述集合进行groupBy并尝试使用INVOICE_NUMBER和行作为值来实现地图,代码下面是

def lines = invoices*.split('\\|').findAll{ it.size()>1 }
def heads = lines.first()
def invoiceMap =  lines.tail().collect{ [heads, it].transpose().collectEntries() }.groupBy{ it.INVOICE_NUMBER }

如果我打印invoiceMap我得到了我想要的地图

 [INV-Error_Test1:[[LINE:1, INVOICE_DATE:20150301, INVOICE_NUMBER:INV-Error_Test1, INVOICE_TOTAL:22], 
                   [LINE:2, INVOICE_DATE:20150301, INVOICE_NUMBER:INV-Error_Test1, INVOICE_TOTAL:24]], 
  INV-Error_Test2:[[LINE:3, INVOICE_DATE:20150301, INVOICE_NUMBER:INV-Error_Test2, INVOICE_TOTAL:26], 
                   [LINE:4, INVOICE_DATE:20150301, INVOICE_NUMBER:INV-Error_Test2, INVOICE_TOTAL:28,]]
  ]

但是如果INVOICE_NUMBERinvoices地图中有任何空格,我的代码就不起作用了。有人可以帮助我使用INVOICE_NUMBER上的空白区域来处理我的代码吗?

2 个答案:

答案 0 :(得分:2)

使用正确的CSV解析器,而不是自己动手。

@Grab('com.xlson.groovycsv:groovycsv:1.0')
import static com.xlson.groovycsv.CsvParser.parseCsv

def invoices = [
'LEDES98BI V2',
'LINE|INVOICE_DATE|INVOICE_NUMBER|INVOICE_TOTAL',
'1|20150301|INV-Error_Test1|22',
'2|20150301|INV-Error_Test1|24',
'3|20150301|INV-Error_Test2|26',
'4|20150301|INV-Error_Test2|28,']

def data = parseCsv(invoices.drop(1).join('\n'), separator:'|')
def invoiceMap = data.collect().groupBy { it.INVOICE_NUMBER }

或列标题中有空格:

def invoices = [
'LEDES98BI V2',
'LINE|INVOICE_DATE|INVOICE NUMBER|INVOICE_TOTAL',
'1|20150301|INV-Error_Test1|22',
'2|20150301|INV-Error_Test1|24',
'3|20150301|INV-Error_Test2|26',
'4|20150301|INV-Error_Test2|28,']

def data = parseCsv(invoices.drop(1).join('\n'), separator:'|')
def invoiceMap = data.collect().groupBy { it.'INVOICE NUMBER' }

答案 1 :(得分:0)

你只需要引用你的名字,就像这样

with open('CSVFile1.csv', 'rb') as csvfile:

    fh = csv.reader(csvfile)
    wfh = open('CSVFile2.csv', 'ab')

    for row in fh:
        if user_input in row[3] and int(integer_input) > 5:
            row.append(integer_input)
            writer = csv.writer(wfh)
            writer.writerow(row)

    wfh.close()