我正在使用 java 将 .csv 文件拆分为训练集和测试集。我已经研究过,但没有找到任何简单灵活的方法来做到这一点,python中有很多代码,但在java中没有找到任何代码。有没有什么方法可以轻松理解代码来做到这一点
最佳答案
public static void main(String args[]){
String fileName= "Archivos/Students.csv"; //Depends on your file location
BufferedReader inputStream = null;
try{
inputStream= new BufferedReader(new FileReader(fileName));//se abre el Stream de lectura
String line = null;
System.out.println("Reading "+fileName);
while((line=inputStream.readLine()) != null){
String[] dataLine = line.split(",");
for (int i=0;i<dataLine.length;i++){
System.out.println(line); //Reads each line from the csv File
System.out.println("Name: "+dataLine[0]);
System.out.println("Last Name: "+ dataLine[1]);
System.out.println("ID: "+dataLine[2]);
System.out.println("State of residence: "+ dataLine[3]);
System.out.println("");
}
}
} catch(FileNotFoundException ex){
System.out.println("Data "+ fileName +" not found");
} catch(IOException ex){
System.out.println("Error while reading " + fileName);
}finally{
//Close the Stream into a try-catch because it can throw an IOException
try{
inputStream.close();
} catch(IOException ex){
Logger.getLogger(Student.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
This is what my csvFile contains
基本上只需将“.split(",")”应用于您从 csv 文件中读取的行(代码中的第 10 行)。
关于java - 如何从 .csv 文件中拆分数据集以用于 Java 中的训练和测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52789790/