Solved

how to count the repeated words from the text file using java program

Posted on 2010-09-03
5
2,089 Views
Last Modified: 2012-05-10
Sir,
      I do my project in data mining, pls give the java program for count the repeated words from the  text file. For example, the file in ‘D’ colon, then we retrieve that text file and count the total no of repeated words and display the text area in java program.
      For ex:
            Hai – 6, good-2, world-5………………..
0
Comment
Question by:sunda2010
5 Comments
 
LVL 92

Accepted Solution

by:
objects earned 125 total points
Comment Utility
Read the file word by word

http://helpdesk.objects.com.au/java/using-scanner-to-read-words-from-text-file

And use a Map to store the word counts
0
 
LVL 40

Expert Comment

by:gurvinder372
Comment Utility
You have already accepted these solution, which are giving the same solution
http://www.experts-exchange.com/Programming/Languages/Java/Q_26449362.html
http://www.experts-exchange.com/Programming/Languages/Java/Q_26446914.html

Why can't you use them?
0
 
LVL 2

Expert Comment

by:chataros
Comment Utility
you will find how you can read the file using google.
the algorithm is something like this:
import java.util.HashMap;

public class count
{

    /**
     * @param args
     */
    public static void main(String[] args)
    {
        String fileContents = "asd aaa asd aaa asd";
        HashMap<String, Integer> wordCount = new HashMap<String, Integer>();
        String[] words = fileContents.split(" ");
        for (String word : words)
        {
            if (wordCount.containsKey(word))
            {
                Integer oldCount = wordCount.get(word);
                wordCount.put(word, oldCount + 1);
            }
            else
            {
                wordCount.put(word, 1);
            }
        }
    }

}
0
 

Expert Comment

by:ikraammomin
Comment Utility
import java.util.HashMap;
import java.io.*;

public class WordCount
{

   public static void main(String[] args) throws Exception
   {
      FileReader fr = new FileReader("D:\abcd.text");
      String fileContents = "";
      String line = fr.readLine();
      while (line != null) {
            fileContents = fileContents + line;
            line = fr.readLine();
      }

       HashMap<String, Integer> wordCount = new HashMap<String, Integer>();
       String[] words = fileContents.split(" ");
       for (String word : words)
       {
           if (wordCount.containsKey(word))
           {
               Integer oldCount = wordCount.get(word);
               wordCount.put(word, oldCount + 1);
           }
           else
           {
               wordCount.put(word, 1);
           }
       }
   }

}
0
 
LVL 6

Expert Comment

by:__geof__
Comment Utility
Quite the same answer as the other question: http://www.experts-exchange.com/Programming/Languages/Java/Q_26446916.html?cid=1131#a33594515
Just change the input to be a file instead of System.in
###

### CustomEntry class that implements comparable to be able to sort it afterwards and a method to change a Map to a List of CustomEntry

###



public class CustomEntry implements Comparable {



    private Map.Entry entry;



    public CustomEntry(Map.Entry entry) {

        this.entry = entry;

    }



    public Map.Entry getEntry() {

        return this.entry;

    }



    public int compareTo(CustomEntry anotherEntry) {

        Integer thisIntegerVal = (Integer) (this.getEntry().getValue());

        int thisVal = thisIntegerVal.intValue();

        Integer anotherIntegerVal = (Integer) (anotherEntry.getEntry().getValue());

        int anotherVal = anotherIntegerVal.intValue();

        return (thisVal < anotherVal ? 1 : (thisVal == anotherVal ? 0 : -1));

    }



    public int compareTo(Object o) {

        return compareTo((CustomEntry) o);

    }



    public static List<CustomEntry> convertMapToList(Map map) {

        List<CustomEntry> list = new ArrayList();

        Set entrySet = map.entrySet();

        Iterator iterator = entrySet.iterator();

        while (iterator.hasNext()) {

            Map.Entry entry = (Map.Entry) iterator.next();

            CustomEntry customEntry = new CustomEntry(entry);

            list.add(customEntry);

        }

        return list;

    }

}





###

### The main method that creates the Map from the string than get it sorted and printing them

###



    public static void main(String[] args) {

        HashMap<String, Integer> wordCount = new HashMap<String, Integer>();

        try {

            BufferedReader br = new BufferedReader(new FileReader(D:\file.txt));

            StringBuffer contents = new StringBuffer();

            String text = null;

 

            // repeat until all lines is read

            while ((text = reader.readLine()) != null)

            {

                contents.append(text)

                    .append(System.getProperty(

                        "line.separator"));

            }

            String str = contents.toString();

            String[] words = str.split(" ");

            for(String word:words){

                if(wordCount.containsKey(word)){

                    Integer i = wordCount.get(word) + 1;

                    wordCount.remove(word);

                    wordCount.put(word, i);

                }else{

                    wordCount.put(word, 1);

                }

            }

            List l = CustomEntry.convertMapToList(wordCount);

            Collections.sort(l);

            for(int i = 0; i < l.size(); i++){

                CustomEntry entry = (CustomEntry) l.get(i);

                System.out.println(entry.getEntry().getKey() + " occured " + entry.getEntry().getValue() + " times");

            }

        } catch (FileNotFoundException e) {

            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);

        }

        } catch (IOException ex) {

            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);

        }



    }

Open in new window

0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now