【问题标题】:Counting Occurrences of a word using a input/output program in java使用java中的输入/输出程序计算单词的出现次数
【发布时间】:2015-05-23 08:55:20
【问题描述】:

如何使用输入/输出程序在包含五个或更多字母的文件中找到出现次数最多的单词?这是我拥有的入门代码

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;


public class FileIOtest {

/**
 * @param args
 * @throws FileNotFoundException 
 */
public static void main(String[] args) throws FileNotFoundException {
    // TODO Auto-generated method stub
    File file = new File ("myfile.txt");
    Scanner inputFile = new Scanner(file);

    while(inputFile.hasNext())
    {
        String str =inputFile.nextLine();
        System.out.println(str);
    }
    inputFile.close();

}

}

【问题讨论】:

    标签: java file-io input io find-occurrences


    【解决方案1】:

    我会创建一个hashmap,它在单词和出现次数计数器之间保存一个键值对。

    Map<String, Integer> myMap = new HashMap<String, Integer>();
    

    您应该用空格分割每一行,然后遍历分割字符串的数组。然后,您可以检查单词是否为 5 个或更多字符,并在 hashmap 中增加计数器

        String str = inputFile.nextLine();
        String[] parts = str.split(" ");
        for(int x  = 0; x < parts.length; x++)
        {
            String word = parts[x];
           if(word.length() >= 5)
           {
               if(myMap.containsKey(word))
               {
                  myMap.put(word, myMap.get(word) + 1);
               }
               else
               {
                  myMap.put(word, new Integer(1));
               }
           }
        }
    

    然后在最后你可以使用myMap.entrySet() 获得HashMap 的内部集。然后在该集合中进行交互以找到第一个、第二个、第三个等最常见或最不常见的单词。

    【讨论】:

    • 您还需要删除“语法”字符,例如句号和逗号,这会使单词变大并在地图中创建两个版本。这假定您的文件包含文本,而不仅仅是单词列表。
    最近更新 更多