tO FIND UNIQUE WORDS IN A FILE USING HASHMAP

tO FIND UNIQUE WORDS IN A FILE USING HASHMAP

import java.util.*;
import java.io.*;

public class countunique {

private String[] splitter;   
private int[] counter;   


/*  
 * @param String - represents the sentence to be parsed  
 *  
 */  
public void countWords(String text){   

    // remove any '\n' characters that may occur   
    String temp = text.replaceAll("[\\n]", " ");   

    // replace any grammatical characters and split the String into an array   
    splitter = temp.replaceAll("[.,?!:;/]", "").split(" ");   

    // intialize an int array to hold count of each word   
    counter= new int[splitter.length];   

    // loop through the sentence   
    for(int i =0; i< splitter.length; i++){   

        // hold current word in the sentence in temp variable   
        temp = splitter[i];   

            // inner loop to compare current word with those in the sentence   
            // incrementing the counter of the adjacent int array for each match   
            for (int k=0; k< splitter.length; k++){   

                if(temp.equalsIgnoreCase(splitter[k]))   
                {   
                    counter[k]++;   
                }   
            }   
    }   

    printResults();   
}   


private void printResults()   
{   

  // create a HashMap to store unique combination of words and their counter   
  // the word being the key and the number of occurences is the value   
  HashMap map = new HashMap();   
  int cc=0;
  // populate the map   
  for (int i=0; i< splitter.length; i++)   
  {   
      map.put(splitter[i].toLowerCase(), counter[i]);   
  }   

  // create an iterator on the map keys   
  Iterator it = map.keySet().iterator();   

    System.out.println("Word             Count");   
    System.out.println("-----------------------");   

    // loop for each key   
    while(it.hasNext())   
    {   
          cc++;

        String temp =(String)it.next();   

        // print the word itself   
        System.out.print(temp);   

         // add relevant spacing to print consistently   
        for (int i=0;i< (20 - temp.length());i++)   
        {   
            System.out.print(" ");   
        }   

        // print the value (i.e. count of each word)   
        System.out.println(map.get(temp.toString()));

    } 
    System.out.println("Number of unique words in file "+cc);
}   



// main method to test the class   
public static void main(String[] args){  
    String f="";
    String space=" ";
     String str=null;

    try {
          FileInputStream fstream = new FileInputStream("C:/Documents and Settings/549176/Desktop/test.txt");
          DataInputStream in = new DataInputStream(fstream);
          BufferedReader br = new BufferedReader(new InputStreamReader(in));

          while ((str = br.readLine()) != null) {

              f=f.concat(str);
              f=f.concat(" ");
            //System.out.println(str);
          }
          in.close();
        } catch (Exception e) {
          System.err.println(e);
        }

    countunique wc = new countunique();   

    wc.countWords(f);   

}

}

View Answers

April 24, 2012 at 5:46 PM

import java.io.*;
import java.util.*;

public class CountWordOccurrence {
        public static void main(String[] args){
try{
       BufferedReader br=new BufferedReader(new FileReader("c:/data.txt"));
       String str="";
        String st;
        while((st=br.readLine())!=null){
            str+=st+" ";
        }
        HashMap<String, Integer> map = new HashMap<String, Integer>();


            str = str.toLowerCase(); 
                int count = -1;
                for (int i = 0; i < str.length(); i++) { 
                   if ((!Character.isLetter(str.charAt(i))) || (i + 1 == str.length())) { 
                            if (i - count > 1) { 
                            if (Character.isLetter(str.charAt(i))) 
                                i++;
                            String word = str.substring(count + 1, i);
                            if (map.containsKey(word)) { 
                            map.put(word, map.get(word) + 1);
                            }
                            else { 
                            map.put(word, 1);
                            } 
                        } 
                        count = i;
                    } 
                } 
        ArrayList<Integer> list = new ArrayList<Integer>();
        list.addAll(map.values());
        Collections.sort(list, Collections.reverseOrder());
        int last = -1;
        for (Integer i : list) { 
            if (last == i) 
                continue;
            last = i;
            for (String s : map.keySet()) { 
                if (map.get(s) == i) 
                    System.out.println(s + ":" + i);
            } 
        }
}
catch(Exception e){
System.out.println(e);
}
    } 
}









Related Tutorials/Questions & Answers:
tO FIND UNIQUE WORDS IN A FILE USING HASHMAP
tO FIND UNIQUE WORDS IN A FILE USING HASHMAP  import java.util....() { // create a HashMap to store unique combination of words...())); } System.out.println("Number of unique words in file "+cc
Program to count the number of unique words in a file using HashMap
Program to count the number of unique words in a file using HashMap  ...()); System.out.println("The number of unique words: "+uniqueValues.size...[]) throws FileNotFoundException { File f = new File("C:/547647/word
Advertisements
Find the percentage of words which starts with a vowel in a file
Find the percentage of words which starts with a vowel in a file   Question: Find the percentage of words which starts with a vowel in a file. Ex: Input: Contents of File1- There is an endless loop in the program. Output: Vowel
find all unique character in string using java
find all unique character in string using java  example: hello how are you. output should be waryu
Problem while using a HashMap for writing text ina RTF file. - Framework
Problem while using a HashMap for writing text ina RTF file.  Hi, I am trying to generate a RTF file using iText.jar, wherein I am taking... matched to the string then only write to the RTF file. Problem is Document writes
program to display frequency count of each word in a file using Hashmap, Hashset and streamtokenizer.plz help me out ..
program to display frequency count of each word in a file using Hashmap...) { System.out.println("Enter word to search in given file(to stop words... above program with HashMap read the words from console based on key and value(ex
Need to find the position of delimiter in a file using java - Java Beginners
Need to find the position of delimiter in a file using java  Hi , will any one give me a solution to find the Need to find the position of delimiters in a file using java.Please do reply
display co-occurrence words in a file
display co-occurrence words in a file  how to write java program for counting co occurred words in the file
display co-occurrence words in a file
display co-occurrence words in a file  how to write java program for counting co occurred words in the file
retrieve kv pairs using hashmap
retrieve kv pairs using hashmap  i want to retrieve k,v-pairs from a hashmap. the entrys are like this: a = 3,4 b = 5,6 and so on. i need combinations of these values. a=3, b=5. a=3, b=6. a=4, b=5. a=4, b=6. I don't know
highlight words in an image using java
highlight words in an image using java  Hai all,In my application left side image is there and right side an application contains textboxes like... want to highlight name in the image using java/jsp/javascript.please help me
HashMap
HashMap  How to work hashmap and hashset internally
Java count words from file
Java count words from file In this section, you will learn how to determine the number of words present in the file. Explanation: Java has provides several... by using the StringTokenizer class, we can easily count the number of words
Breaking a string into words without using StringTokenizer
Breaking a string into words without using StringTokenizer  how can we Break a string into words without using StringTokenizer ??   The given code convert the string into words. import java.util.*; class StringExample
hashmap
hashmap  write a program that shows the use of Hashmap class
how to count words in string using java
how to count words in string using java  how to count words in string using corejava   Hi Friend, Try the following code: import...++; } System.out.println("Number of words are: "+count); } } Thanks   Hello
HASHMAP
HASHMAP  HI CAN WE ADD PRIMITIVE DATA TYPE IN HASHMAP IN JAVA 1.5 VERSION . THANKS KALINS NAIK   Java HashMap Example
java program to insert data into a file and count the number of words from the file???????
java program to insert data into a file and count the number of words from the file???????  java program to insert data into a file and count the number of words from the file
Hashmap
Hashmap  Hi i want to date and day in hashmap , 1 want to display according to day with date, how to write aprograme
Hashmap
args[]){ HashMap hm=new HashMap(); hm.put(new Integer(2), "Two"); hm.put...*; public class HashTable { public static void main(String args[]){ HashMap hm=new HashMap(); hm.put(new Integer(2), "Two"); hm.put(new Integer(1
HashMap
HashMap  How can you get a HashMap to Display Text onto a Text Field that is defined and Set up to JPanel on a different Class static class public static Map <String, ActionListener> listener = new HashMap <String
how to load a table of data from oracle, to a jsp page using hashmap.
how to load a table of data from oracle, to a jsp page using hashmap.  I have a jsp page which ask for project ID,team name,member name according... to use the hashmap.How can i convert a result set object to hashmap object
Display non-duplicate words from file
Display non-duplicate words from file In this tutorial, you will learn how to read a text file and display non-duplicate words in ascending order. The given... object is then passed to StringTokenizer which broke the text of file into words
Unable to bind to a hashmap from jsp using spring tags - Spring
Unable to bind to a hashmap from jsp using spring tags  Hi, I am unable to bind a hashmap from my jsp page. Here is what i want to do: I have... to bind with the hashmap dynamically.) On submission of the form i need the label
program to display all words in the file in the sorted order without duplicates
program to display all words in the file in the sorted order without duplicates  I want a java program which accepts a file from user and displays all words in the file in the sorted order without duplicates
Collection : HashMap Example
key and corresponding value. By using size() method we can find out number...Collection : HashMap Example This tutorial will help you in understanding of HashMap concept. HashMap : The java.util.HashMap class implements Map
Map words to line number in text file and show occurence
Map words to line number in text file and show occurence  hi i want to Map words to line number in text file and show occurrence of word in java coding
Java reverse words in a string using only loops
Java reverse words in a string using only loops In this tutorial, you will learn how to reverse words in a string without using any inbuilt methods like split() etc, StringTokenizer functiom or any extra ordinary function Only loops
How to get unique list in Hibernate using Criteria Query?
How to get unique list in Hibernate using Criteria Query?  Hi, Share me the example code for getting Unique List in Hibernate through Criteria Query? Thanks
To find palindrome no in a file - Java Beginners
To find palindrome no in a file  hi all i am having a problem...I wanted to write one java program where i have to count the no of palindrome in a file. I tried it with my own but not able to get result.pls help me out  
Find Browser & it's version using jQuery
Find Browser & it's version using jQuery  Hi sir I heard that JQuery have some method which can be used to find the Browser name & its version. I need the code which checks the browser and if it is "Mozilla", it will show
How to store unique values in Java using Set?
Store unique values in Java using Set interface In this section we... will show you how to store unique values in Java using Set? The Set interface... the unique values. Here is the example program to store unique values in Java using
How to store unique values in Java using Set?
Store unique values in Java using Set interface In this section we... will show you how to store unique values in Java using Set? The Set interface.... In this tutorial you have learned to store unique values in Java using the HashSet object
Java hashmap, hashtable
Java hashmap, hashtable  When are you using hashmap and hashtable
putting words to line number form a java file/test file and show occurrence
putting words to line number form a java file/test file and show occurrence  hi all i want putting words to line number form a java file and show occurrence but i cant use mapping method i can only use the LinkedList
HashMap in Java
HashMap class is used to implement Map interface. The value of HashMap is stored using get() and put(). HashMap provides key-value access to data. HashMap is almost equal to HashTable, the only difference is that HashMap allows null
Find number of words begin with the specified character
Count number of words begin with the specified character In this section, you will learn how to count the number of words that begin with the specified... or a string and a character to search. Using StringTokenizer class, we have break
HashMap - Struts
HashMap  Can you please get me an example code for using HashMap in Jsp and what for what purpose it is used
How to find a config file in spring project
How to find a config file in spring project  how to find configuration file in the spring project
find a substring by using I/O package
find a substring by using I/O package  Write a java program to find a sub string from given string by using I/O package
how to find which user has modified the file
how to find which user has modified the file  how to find which user has modified the file
Uploading a file using UploadBean
Uploading a file using UploadBean  Dear sir, In my project i have to upload the file and use the same file for getting a values from... upload the file and use the file for getting values it will throws
Program to find no of metrics in a file ----- Java code
Program to find no of metrics in a file ----- Java code  Hi Friends, I got a task to calculate the metrics of a program, like to find... the no of SELECT and INSERT statements but unable to find tablewise. E.G Table
find zip file length lessthen 5MB
find zip file length lessthen 5MB  import java.io.BufferedReader... File folder = new File(source); if(folder.exists... :"); detination=readkeyboard.readLine(); File[] files
find factorial of any number using recursion
find factorial of any number using recursion  error in 14 line ; expected int rec( int a) ^ how to resolve this.please correct the code. import java.io.*; class Fact { public static void main(String[]arg)throws IOException
file upload using JSP
file upload using JSP  I have created a form to upload a file in a html page, now i want to get the path of the file in a jsp page so what code...="java" %> <HTML> <HEAD><TITLE>Display file upload form
file uploading using jsp
file uploading using jsp  below file uploading code has one error... = " + formDataLength); //String file = new String(dataBytes); //out.println("FileContents:" + file +""); byte[] line = new byte[128]; if (totalBytesRead
servlet,jsp login registration forms without database in ecalipse ide using hashmap to store the registraion details ?
servlet,jsp login registration forms without database in ecalipse ide using hashmap to store the registraion details ?   first registration with email , username, password after >> <> without
servlet,jsp login registration forms without database in ecalipse ide using hashmap to store the registraion details ?
servlet,jsp login registration forms without database in ecalipse ide using hashmap to store the registraion details ?   first registration with email , username, password after >> <> without
servlet,jsp login registration forms without database in ecalipse ide using hashmap to store the registraion details ?
servlet,jsp login registration forms without database in ecalipse ide using hashmap to store the registraion details ?   first registration with email , username, password after >> <> without

Ads