繁体   English   中英

使用OpenCSV从CSV提取特定数字

[英]Using OpenCSV to extract specific numbers from CSV

我有带有标题和特定编号的CSV文件。 我需要分别提取这些数字以创建一个AIM XML文件,但这并不重要。 我很难尝试根据其标题提取数字。 我已经尝试了各种方法,但是无法正常工作。 当我尝试运行此代码时(以下仅是示例),它似乎从未终止。 我对Java或OpenCSV不太熟悉,所以请原谅您所见的混乱情况。 (也是凌晨2点,我的大脑出现了故障)

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import edu.stanford.hakan.aim3api.base.AimException;
import edu.stanford.hakan.aim3api.base.ImageAnnotation;
import edu.stanford.hakan.aim3api.usage.AnnotationBuilder;
import au.com.bytecode.opencsv.CSVReader;



public class CreateAIMFile {
public static void main(String[] args) throws IOException, FileNotFoundException,     AimException
{
    ImageAnnotation PeserAnnotation1 = new ImageAnnotation ();
    String csvFilename = "C:/Users/Daniela/Documents/ISPY/205_4493_MR1_ACRIN_6657/E25008/peser_data.csv"; //Insert file name and location
    CSVReader csvReader = new CSVReader(new FileReader(csvFilename));
    String [] nextLine = csvReader.readNext();

    //start 
    for (int i = 0; i<50; i++){ //i<50 is a random number
        while (nextLine[i] != null){
            if (nextLine[i] == "CagridId") //customize name
            {
                CSVReader csvreader = new CSVReader(new FileReader(csvFilename), ';', '\'', 1);
                Integer A = Integer.valueOf(nextLine[i]);
                PeserAnnotation1.setCagridId(A); 
            }
            else
            {
            PeserAnnotation1.setCagridId(0); 
            }
        }
    }
    for (int i = 0; i<50; i++){ 
        while (nextLine[i] != null){
            if (nextLine[i] == "PatientComment") //customize name
            {
                CSVReader csvreader = new CSVReader(new FileReader(csvFilename), ';', '\'', 1);
                PeserAnnotation1.setComment(nextLine[i]); 
            }
        else
            {
                PeserAnnotation1.setComment("");
            }
        }
    }
AnnotationBuilder.saveToFile(PeserAnnotation1, "./AIMFileName.xml", "AIM_v3.xsd");     //customize name of XML file
    System.out.println(AnnotationBuilder.getAimXMLsaveResult());
}
}

通常,通过实例化CSVReader对象将打开CSV文件一次,然后循环调用readNext文件。

在您的代码中,您将在循环中重新实例化CSVReader,而不在循环中调用readNext。

我认为您在混淆csvReader.readNext(); 与csvReader.readAll();

试试这个(不编译!):

String headerLine = csvReader.readNext();

List numbersInHeader = new ArrayList();
for(int i = 0 ; i < headerLine.length ; i++){
    if(headerLine[i].equals("YouHeaderNameHere") || headerLine[i].equals("OtherNumberHeader")){
        numberInHeader.add(i);
    } 
}
String line[] = null;
while((line = csvReader.readNext()) != null){
    for(int i = 0 ; i < line.length ; i++){
        if(numbersInHeader.contains(i)){ 
            // This is a number do you work here

        }

    }
}

希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM