【问题标题】:Word Length Frequency字长频率
【发布时间】:2015-08-13 10:35:37
【问题描述】:

我在 Eclipse 中创建了一个 Java 程序。该程序计算每个单词的频率。例如,如果用户输入“我去商店”,程序将产生输出“1 1 1 2”,即 1 个长度为 1 的单词 ('I') 1 个长度为 2 的单词 ('to') 1 个单词长度为 3('the')和 2 个长度为 4 的单词('went','shop')。

我创建了这个程序来读取用户输入的字符串,但我想调整代码以读取文本文件的每一行。任何帮助都会很棒。

import java.util.Scanner;

public class WordLengthFrequency
{

    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);

        while (true)
        {
            System.out.println("Enter text: ");

            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;
            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++){    
                StringBuilder sb = new StringBuilder(i).append(i + " letter words: ");
                for (int j = 1; j <= counts[i]; j++) {
                    sb.append('*');
                    System.out.println(i + " letter words: " + counts[i]);
                    System.out.println(sb);
                    System.out.println(("mean lenght: ") + ((double) total / strings.length));
                }
            }
       }
    }
}

【问题讨论】:

  • Best way to read a text file 的可能重复项
  • 只需将Scanner scan = new Scanner(System.in); 替换为Scanner scan = new Scanner(new File("file path here"));。简单快捷的方法
  • 谢谢!但现在我得到一个错误:线程“main”中的异常 java.util.NoSuchElementException:在 mallinson_Liam_8.main(mallinson_Liam_8.java:16) 的 java.util.Scanner.nextLine(Scanner.java:1516) 处找不到行
  • 您可以使计算 wordLenghts 的逻辑更容易(如果您可以使用 java8)Map&lt;Integer, Long&gt; collect = Arrays.stream(strippedInput.split(" ")).collect( Collectors.groupingBy(String::length, Collectors.counting()));。其中 Map 中的 Integer Value 是单词的长度,long-value 是出现次数

标签: java eclipse text-files word-frequency


【解决方案1】:

第一个提示,一点代码格式可以对可读性产生巨大的影响。另外,对于读取文件,我建议使用BufferedReader。在这种情况下,我建议使用HashMap。目前,您受限于可以跟踪的单词长度,因为您使用的是具有有限索引的列表。使用地图,您可以跟踪任意长度的单词。像下面这样的东西会很好。

public static void main(String[] args) {
    HashMap<Integer, Integer> lengthCount = new HashMap<Integer, Integer>();
    BufferedReader br;
    try {
        String currentLine;
        br = new BufferedReader(new FileReader("text.txt"));

        // Gets new line, if it is the end of the file, it ends
        int totalNumberWords = 0;
        while ((currentLine = br.readLine()) != null) {
            String[] words = currentLine.split(" ");
            totalNumberWords += words.length;

            // Iterates through the words in the line and
            // increments the map appropriately
            for (String word : words) {
                int currentNumber = 0;
                if (lengthCount.get(word.length()) != null)
                    currentNumber = lengthCount.get(word.length());
                lengthCount.put(word.length(), currentNumber + 1);
            }
        }

        // Iterates through the map and prints the amount of strings
        // for each length and the percent of words with each length
        for (Map.Entry<Integer, Integer> curEntry : lengthCount.entrySet()) {
            double percentWithThisLength = ((double) curEntry.getValue() / totalNumberWords) * 100;
            System.out.print(curEntry.getValue() + " string(s) with length " + curEntry.getKey());
            System.out.println(" (" + percentWithThisLength + "%)");
        }

        br.close();
    } catch (IOException e) {
        System.out.println("Could not find specified file");
    }
}

text.txt 包含:

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua。耶

产生:

3 string(s) with length 2 (15.0%)
3 string(s) with length 3 (15.0%)
6 string(s) with length 5 (30.0%)
3 string(s) with length 6 (15.0%)
2 string(s) with length 7 (10.0%)
2 string(s) with length 10 (10.0%)
1 string(s) with length 11 (5.0%)

【讨论】:

    【解决方案2】:
    Scanner scan = new Scanner(System.in);
    

    此代码创建了一个扫描器,用于扫描 system.in 以获取要读取的内容。 System.in 通常是控制台。相反,您想从其他地方阅读,因此您需要将扫描仪指向您想要的文本。

    这很容易做到

    Scanner scan = new Scanner(new File("filePath"));
    

    您还需要更改循环,因为您不能永远继续下去(文件,与控制台输入不同,最终会结束)。 Scanner 有一个不错的小方法,hasNext(),它会告诉你它是否有更多的行要读取。

    【讨论】:

    • 谢谢,但我现在收到此错误:“线程“主”java.util.NoSuchElementException 中的异常:在 mallinson_Liam_8 的 java.util.Scanner.nextLine(Scanner.java:1516) 处找不到行。主要(mallinson_Liam_8.java:16)“
    • 一旦到达行尾,您将收到该错误。您可以通过将 while(true) 更改为 while(scan.hasNext()) 来停止此操作,无论扫描仪是否有更多行,它都会返回。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-07
    • 2012-11-20
    • 2011-04-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多