如何在Java中计算文件中单词的长度?

3
我将尝试编写一段代码,以计算文件中特定长度单词的数量。
例如:
How are you?

会打印出以下内容:
Proportion of 3-letter words: 100%  (3 words)

我想要统计长度为1、2、3、4、5、6、7、8、9、10、11、12和13+的单词数量。

你能指导一下我吗?

我不是在尝试找到单词的数量。我已经可以使用以下代码完成:

public static int WordCount() throws FileNotFoundException
{
    File file = new File("sample.txt");
    Scanner keyboard = new Scanner(new FileInputStream(file));
    int count=0;
    while(keyboard.hasNext())
    {
      keyboard.next();
      count++;
    }
    return count;
}

我想要找到一定长度的单词。 更新 我已经写了以下代码:
public static int WordLengthCount() throws FileNotFoundException
{
  File file = new File("hello.txt");
  Scanner keyboard = new Scanner(new FileInputStream(file));
  int count5 = 0;
  int hell = 0; //This is just for the else command to compile

  while(keyboard.hasNext())
  {
    if ( keyboard.next().length() == 5 )
    {
      count5++;
      keyboard.next();
      return count5;
    }
  } return hell;
}

3
展示你已经尝试了什么? - Shriram
1
可能是Count words in a string method?的重复问题。 - ted
@VictorSmt 不,我不想找到所有的单词,我想要找到特定长度的单词。 - Saadat
@Shriram 我编辑了我的帖子。 - Saadat
@Saadat,您可以将单词添加到列表中,然后按长度进行排序。 - Madhawa Priyashantha
显示剩余6条评论
4个回答

2
你可以使用length()方法来计算字符串(单词)中的字符数。然后,只需要将它保存在某个地方即可,例如在Map中:
public static Map<Integer, Integer> lengthCounts() throws FileNotFoundException
    Map<Integer, Integer> countMap = new HashMap<>();
    while(keyboard.hasNext())
    {
        String word = keyboard.next();
        int length = word.length();
        Integer currCount = countMap.get(length);
        if (currCount == null) {
            countMap.put (length, 1);
        else {
            countMap.put (length, currCount + 1);
        }
    }
    return countMap;
}

现在您可以检查任何特定长度的单词数量,甚至打印所有单词。
编辑:
如果您只需要某个长度的单词百分比,您只需要两个计数器 - 一个用于该长度的单词,另一个用于所有单词:
public static double lengthPercentage(int requiredLength) throws FileNotFoundException
    int allWords = 0;
    int requiredWords = 0;
    while(keyboard.hasNext())
    {
        String word = keyboard.next();
        int length = word.length();
        if (length == requiredLength) {
            ++requiredWords;
        }
        ++allWords;
    }
    // implicit assumption: there's at least on word in the file
    return ((double) requiredWords) / allWords;
}

有没有不使用映射的方法来实现这个?我会更新我的问题,你能帮忙看一下吗?谢谢。 - Saadat
我已经编辑了这个问题,并加上了 更新,你能看一下吗? - Saadat
@Saadat,我现在更好地理解了你的问题——请看我的编辑答案。 - Mureinik
谢谢。问题已解决 :) - Saadat

0
File file = new File("sample.txt");
    Scanner keyboard = new Scanner(new FileInputStream(file));
    int count=0;
    while(keyboard.hasNext())
    {
      keyboard.next();
      // Use a hash map
      // Check the string length and add it to the hash map by checking it already exists. If already exists then get the actual value from hashmap and increment it by one and save it again to the map.

      count++;
    }

这样你的最终输出将是一个包含单个字母字符串计数、两个字母字符串计数等的映射。


我已经编辑了问题并更新了,你能看一下吗? - Saadat

0
其他答案都很好,但如果您想在文件中查找特定长度的单词并且不喜欢上面的答案,则也可以尝试使用正则表达式。 您可以测试每个单词,然后对其进行处理。 如果您要查找每个长度文件中单词的数量,则上面的答案更好,但如果您要检测特定长度的单词,则可以使用.length()或下面的正则表达式。 在我看来,使用字符串的.lenght()函数更好,但我只是提供另一种答案和示例。
我会放一个小例子在下面。
public class Words{
    public static void main(String [] args){
        String [] words = {"Pizzaaa", "Pizza", "Party"};
        int fives = 0;
        for( String s : words){
            if(s.matches(".{5}")){
                5++;

            }
        }
       System.out.println(fives);
    }
}

或者更好的版本:

public class Words{
    public static void main(String [] args){
        String [] words = {"Pizzaaa", "Pizza", "Party"};
        int fives = 0;
        for( String s : words){
            if(s.length() == 5){
                5++;

            }
        }
       System.out.println(fives);
    }
}

下面进行编辑:演示如何在基于文件的循环中使用它

// other code needed
while(in.hasNext())
{
  String s = in.next();
  if(s.length() == 5)
      fives++;
}

嗨,我如何在文件中使用这个? - Saadat
@Saadat,只需将if语句复制并粘贴到您的代码中即可。您可以将if(s.lenth()== 5)放入具有hasNext()的循环中。 - Pumphouse

0
例如,我有一个名为TextFile.txt的文本文件,位于C:\,其内容如下:
Ut porttitor libero sodales quam sagittis, id facilisis lectus semper.

以及Java代码:

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class Example {

    public static void main(String[] args) throws IOException {
        File file = new File("C:\\TextFile.txt");
        FileInputStream fis = new FileInputStream(file);
        BufferedInputStream bis = new BufferedInputStream(fis);
        DataInputStream dis = new DataInputStream(bis);    

        if (dis.available() != 0) {
            // Get the line.
            String s = dis.readLine();
            // Put words to array.
            String[] sParts = s.split(" ");
            // Initialize word longest length.
            int longestLength = 1;
            for (String strx : sParts) { // Go through each sPart, the next one is called strx
                // If the document has word longer than.
                if (longestLength < strx.length())
                    // Set new value for longest length.
                    longestLength = strx.length();
            }
            // Because array index from "0".
            int[] counts = new int[longestLength + 1];
            for (String str : sParts) {
                // Add one to the number of words that length has
                counts[str.length()] += 1;
            }
            // We use this type of loop since we need the length.
            for (int i = 1; i < counts.length; i++) {
                System.out.println(i + " letter words: " + counts[i]);
            }
        }
    }
}

// Result:
//        1 letter words: 0
//        2 letter words: 2
//        3 letter words: 0
//        4 letter words: 1
//        5 letter words: 0
//        6 letter words: 2
//        7 letter words: 2
//        8 letter words: 0
//        9 letter words: 3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接