【问题标题】:How can I count the number of integer occurences from a txt file from certain columns in Java?java - 如何计算来自Java中某些列的txt文件中的整数出现次数?
【发布时间】:2018-01-08 09:13:36
【问题描述】:

基本上解释一下我有一个txt文档需要读取到文件http://m.uploadedit.com/bbtc/1515402294116.txt

我如何才能专门为第 3 列进行数字计数?比如txt文档第3列从上到下的前10个数字是……

1, 1, 3, 3, 1, 1 ,1, 3, 1, 2

如果我要对 3 的值进行计数,那将是:

"The number 3 occurs: 3 times" 

但是我有一个非常大的样本,我只想将这些值包含在3rd column 中,谁能帮助我我已经被这个问题困扰了一段时间。我认为您必须将每一列设置为数组并以这种方式工作。

【问题讨论】:

    标签: java arrays bufferedreader readfile


    【解决方案1】:

    您的文本文件看起来像制表符分隔,您可以使用BufferedReader 读取每一行并每次提取第三列。使用流可以轻松完成数字计数。

        File file = new File(PATH_TO_TXT);
        ArrayList<Integer> storage = new ArrayList<>();
        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = br.readLine()) != null) {
                String[] arr = line.split("\t");
                storage.add(Integer.valueOf(arr[2].trim()));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    
        Map<Integer, Long> occurrences = storage.stream()
         .collect(Collectors.groupingBy(e -> e, Collectors.counting()));
    

    【讨论】:

    • 您好 Michael,感谢您的回答,我不熟悉按流计数,例如,您如何计算第 3 列中有多少个 4?
    • @jonlajoey 该流将整数映射到该特定整数的计数。您将使用 occurrences.get(4); 返回计数。
    • 代码中的流计算每个数字的出现次数,所以最后你可以使用occurrences .get(4)或将流更改为:storage.stream().filter(e -&gt; e == 4).count()
    • 抱歉,我最后尝试更改了occurrences.get(4),我可能没有把它放在正确的位置,抱歉我是个菜鸟。 ideone.com/eIX3nn你会把它放在哪里?
    • 为什么使用在线IDE而不是本地IDE?您的代码在网站上不起作用,因为您不允许更改类名并将其公开,请将类名保留为 Ideone,试试这个:ideone.com/T6AZtx,但它不起作用,因为您需要一个文件.您应该使用本地 IDE 尝试此代码。
    【解决方案2】:

    如果每个值都用“,”分隔,您可以使用以下代码:

    BufferedReader br = null;
    int counter = 0;
    try {
        br = new BufferedReader(new FileReader("testfile.txt"));
        String line;
        // the column you want to get:
        int column = 3;
        // the value you want to search
        String value = "3";
    
        while ((line = br.readLine()) != null) {
            int first = 0;
            int last = line.indexOf(",");
            //get index of the column
            for (int i = 0; i < column - 1; i++) {
                first = last;
                last = line.indexOf(",", last + 1);
            }
            // get the value of the column
            String column3value = line.substring(first + 1, last);
            // counter +1 for every value
            if (column3value.equals(value)) {
                counter += 1;
            }
        }
        System.out.println(counter);
    } catch (IOException e) {
        e.printStackTrace();
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-22
      • 2014-06-07
      • 2017-03-24
      • 2015-06-19
      • 1970-01-01
      • 1970-01-01
      • 2018-09-09
      相关资源
      最近更新 更多