如何从数据集中删除某些列?

How to remove some columns from a dataset?

我有一个包含文本文件(txt 格式)的大型数据集。 文本文件包含以下格式的数据:

Name, Number, Timestamp, Sensordata1, Sensordata2, ... , Sensordata40
Name, Number, Timestamp, Sensordata1, Sensordata2, ... , Sensordata40
Name, Number, Timestamp, Sensordata1, Sensordata2, ... , Sensordata40

现在我需要从每一行中删除数字和时间戳。

我目前的代码:

try{
            // Open the file that is the first
            // command line parameter

            FileInputStream fstream = new FileInputStream("file.txt");

            // Get the object of DataInputStream
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine;

            //Read File Line By Line
            while ((strLine = br.readLine()) != null)   {

                // Print the content on the console
                System.out.println (strLine);
            }

            //Close the input stream
            in.close();
        }catch (Exception e){//Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }

如何在 Java 中执行此操作?

如果相同的值总是出现在同一列中,那么我相信您可以将所有值添加到 ArrayList,循环删除不需要的值,然后然后把它写回文件。

有几种方法可以完成此操作,具体取决于您要花多长时间检测列等内容,最简单的方法是静态输入要在示例编号 1 和示例 2 中删除的列数组,这可以在您的示例中这样完成:

package stackquestions;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;

 public class StackQuestions {


    public static void main(String[] args) {
       try{
            // Open the file that is the first
            // command line parameter

            FileInputStream fstream = new FileInputStream("file.txt");

            // Get the object of DataInputStream
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine;

            //Read File Line By Line
            while ((strLine = br.readLine()) != null)   {
                String[] data=strLine.split(",");


                for(int i=0;i<data.length;i++){
                    if(i!=1 && i!=2){
                         System.out.println (data[i]);
                    }

                }
                // Print the content on the console

            }

            //Close the input stream
            in.close();
        }catch (Exception e){//Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }
}
}

另一种方法是根据正在读取的行是否为第一行来检测列,拆分第一行(假设正在读取的第一行包含headers,然后对索引进行检查每次迭代查看数据属于哪一列。