Java - частота слов

Я создал программу на Java в Eclipse. Программа считает частоту каждого слова. Например, если пользователь введет "Я пошел в магазин", программа выдаст вывод "1 1 1 2", который представляет собой 1 слово длины 1 ("I") 1 слово длины 2 ("до") 1 слово из длина 3 ("the") и 2 слова длиной 4 ("пошел", "магазин").

Вот результаты, которые я получаю. Я не хочу, чтобы вывод с 0 отображался. Как я могу скрыть это и иметь результаты только с показанными 1,2,3,4,5.

The cat sat on the mat
words[1]=0
words[2]=1
words[3]=5
words[4]=0
words[5]=0


  import java.util.Scanner;
 import java.io.*;

 public class mallinson_Liam_8
{

 public static void main(String[] args) throws Exception
 {

    Scanner scan = new Scanner(new File("body.txt"));

    while(scan.hasNext())
    {

        String s;
        s = scan.nextLine();
        String input = s;
        String strippedInput = input.replaceAll("\\W", " ");

        System.out.println("" + strippedInput);

        String[] strings = strippedInput.split(" ");
        int[] counts = new int[6];
        int total = 0;
        String text = null;

            for (String str : strings)
                if (str.length() < counts.length)
                    counts[str.length()] += 1;
            for (String s1 : strings)
                total += s1.length();   

            for (int i = 1; i < counts.length; i++){  
                System.out.println("words["+ i + "]="+counts[i]);
        StringBuilder sb = new StringBuilder(i).append(i + " letter words: ");
            for (int j = 1; j <= counts[i]; j++) {




    }}}}}

4 ответа

Я знаю, что вы просили Java, но просто для сравнения, вот как я это сделаю в Scala:

val s = "I went to the shop"
val sizes = s.split("\\W+").groupBy(_.length).mapValues(_.size)
// sizes = Map(2 -> 1, 4 -> 2, 1 -> 1, 3 -> 1)

val sortedSizes = sizes.toSeq.sorted.map(_._2)
// sortedSizes = ArrayBuffer(1, 1, 1, 2)

println(sortedSizes.mkString(" "))
// outputs: 1 1 1 2

Добавьте оператор if, который проверяет, равно ли число слов длины 'i' 0.

Если это правда, не показывайте это, если это не так, покажите это.

for (int i =0; i < counts.length; i++) {
 if (counts[i] != 0) {
  System.out.println("words[" + i + "]="+counts[i]); 
 }
}

Редактировать:

Билл бил меня к этому. Наши ответы оба работают.

Я бы использовал потоковый API Java8.

Смотрите мой пример:

// import java.nio.file.*;
import java.util.*;
import java.util.stream.Collectors;

public class CharacterCount {
    public static void main(String[] args) {

        // define input
        String input = "I went to the shop";
        // String input = new String(Files.readAllBytes(Paths.get("body.txt")));

        // calculate output
        String output =

                // split input by whitespaces and other non-word-characters
                Arrays.stream(input.split("\\W+"))

                // group words by length of word
                .collect(Collectors.groupingBy(String::length))

                // iterate over each group of words
                .values().stream()

                // count the words for this group
                .map(List::size)

                // join all values into one, space separated string
                .map(Object::toString).collect(Collectors.joining(" "));

        // print output to console
        System.out.println(output);
    }
}

Это выводит:

1 1 1 2

Просто добавьте чек, прежде чем печатать...

for (int i = 1; i < counts.length; i++) {
    if (counts[i] > 0) { //filter out 0-count lengths
        System.out.println("words["+ i + "]="+counts[i]);
    }
Другие вопросы по тегам