我使用apache commons csv读取从谷歌趋势下载的CSV文件中的内容,该文件位于相关的查询部分右下角。文件的一小部分:
Category: All categories
"bluetooth speakers: (1/1/04 - 8/15/16, Worldwide)"
TOP
speaker,100
bluetooth speaker,100
RISING
portable speakers bluetooth,Breakout
portable speakers,Breakout我要从文件中读取的代码:
private void readCsv(String inputFilePath) {
try {
Reader in = new FileReader(inputFilePath);
Iterable<CSVRecord> records = CSVFormat.RFC4180.withFirstRecordAsHeader().parse(in);
for (CSVRecord record : records) {
String topic = record.get(0);
if (topic != null && !topic.isEmpty()) {
System.out.println(topic);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}产出:
bluetooth speakers: (1/1/04 - 8/15/16, Worldwide)
TOP
speaker
bluetooth speaker
RISING
portable speakers bluetooth
portable speakers期望产出:
speaker
bluetooth speaker
portable speakers bluetooth
portable speakers根据来自google的数据(没有标头)和两个头(、TOP和RISING ),我无法提取所需的值。是否有任何用于筛选的配置,我可以应用以获得所需的值?
发布于 2016-08-15 06:40:36
尽管严格地说,这不是一个好的解决方案,但对于我的情况,忽略具有单个元素的记录消除了标头。我仍然在寻找/正在开发一个解决方案,比如配置或扩展一些类以获得更干净的解决方案。
private void readCsv(String inputFilePath) {
try {
Reader in = new FileReader(inputFilePath);
// Iterable<CSVRecord> records = CSVFormat.RFC4180.withFirstRecordAsHeader().parse(in);
Iterable<CSVRecord> records = CSVFormat.RFC4180.parse(in);
for (CSVRecord record : records) {
if (record.size() <= 1){
continue;
}
String topic = record.get(0);
if (topic != null && !topic.isEmpty()) {
System.out.println(topic);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}这不是一个好的解决方案的原因是因为可能有许多其他的csv文件,这个解决方案可能会被证明是错误的。对某个人来说还是有用的。
https://stackoverflow.com/questions/38950284
复制相似问题