gpt4 book ai didi

csv - 将 SuperCsv 与多个变量列结合使用

转载 作者:行者123 更新时间:2023-12-01 22:43:39 24 4
gpt4 key购买 nike

我正在查看 Super CSV website 中的这个示例这表明 dateofbirth 是可选列。如果我有多个可选列,会发生什么情况?代码将如何变化?

 private static void readVariableColumnsWithCsvListReader() throws Exception {

final CellProcessor[] allProcessors = new CellProcessor[] { new UniqueHashCode(), // customerNo (must be unique)
new NotNull(), // firstName
new NotNull(), // lastName
new ParseDate("dd/MM/yyyy") }; // birthDate

final CellProcessor[] noBirthDateProcessors = new CellProcessor[] { allProcessors[0], // customerNo
allProcessors[1], // firstName
allProcessors[2] }; // lastName

ICsvListReader listReader = null;
try {
listReader = new CsvListReader(new FileReader(VARIABLE_CSV_FILENAME), CsvPreference.STANDARD_PREFERENCE);

listReader.getHeader(true); // skip the header (can't be used with CsvListReader)

while( (listReader.read()) != null ) {

// use different processors depending on the number of columns
final CellProcessor[] processors;
if( listReader.length() == noBirthDateProcessors.length ) {
processors = noBirthDateProcessors;
} else {
processors = allProcessors;
}

final List<Object> customerList = listReader.executeProcessors(processors);
System.out.println(String.format("lineNo=%s, rowNo=%s, columns=%s, customerList=%s",
listReader.getLineNumber(), listReader.getRowNumber(), customerList.size(), customerList));
}

}
finally {
if( listReader != null ) {
listReader.close();
}
}
}

如果可选列不在末尾而是在中心或其他位置怎么办?

最佳答案

因此,这里真正的问题是,要应用正确的单元处理器,您需要知道每列中有哪些数据。对于有效的 CSV 文件(每行的列数相同),这不是问题,但如果您正在处理可变列 CSV 文件,那就很棘手了。

如果像示例一样,只有 1 列是可选的,那么您只需计算读取的列数并使用适当的单元处理器数组。可选列在哪里并不重要,因为它仍然是可预测的。

但是,如果超过 1 列是可选的,那么您就有麻烦了。例如,如果 middleNamecity 在以下 CSV 文件中是可选的:

firstName,middleName,lastName,city
Philip,Fry,New York

可以理解为:

firstName="Philip", middleName="Fry", lastName="New York", city=null

firstName="Philip", middleName=null, lastName="Fry", city="New York"

这不再是可预测的。您也许能够检查列中的数据以确定该列应代表什么(例如,日期有 /),但这不是很可靠,即使如此,您甚至可能必须阅读几行代码就能搞清楚。

关于csv - 将 SuperCsv 与多个变量列结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18200826/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com