Java - 单词频率

时间:2015-07-09 14:42:33

标签: java eclipse word-frequency

我在Eclipse中创建了一个Java程序。该程序计算每个单词的频率。例如,如果用户输入“我去了商店”,程序将产生输出'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 个答案:

答案 0 :(得分:1)

我知道你要求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

答案 1 :(得分:0)

只需在打印之前添加一张支票......

for (int i = 1; i < counts.length; i++) {
    if (counts[i] > 0) { //filter out 0-count lengths
        System.out.println("words["+ i + "]="+counts[i]);
    }

答案 2 :(得分:0)

添加一个if语句,检查长度为“i”的单词数是否等于0。

如果确实如此,请不要显示,如果不是,请显示它。

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

编辑:

bbill打败了我。我们的答案都有效。

答案 3 :(得分:0)

我将使用Java8流API。

参见我的例子:

// 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