tO FIND UNIQUE WORDS IN A FILE USING HASHMAP

Ads
 

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);
}
    } 
}

Ads









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
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
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
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  How to work hashmap and hashset internally
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
HASHMAP
HASHMAP  HI CAN WE ADD PRIMITIVE DATA TYPE IN HASHMAP IN JAVA 1.5 VERSION . THANKS KALINS NAIK   Java HashMap Example
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 i want to date and day in hashmap , 1 want to display according to day with date, how to write aprograme
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
Collection : HashMap Example
Collection : HashMap Example This tutorial will help you in understanding of HashMap concept. HashMap : The java.util.HashMap class implements Map interface. It gives you an unsorted, unordered Map. It provides unique keys to each
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
Find the date of the file before the file has been modified
Find the date of the file before the file has been modified  Hi, may i know is it possible to find the date of the file before the file has been modified?   hi friend, you can get the date of last modified file using
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
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
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
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
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
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
Using the escape percent in the batch file
Using the escape percent in the batch file   If you use the one % in the batch file it will consider it as the parameter input and will try to find the variable and replace it. But how to use the percentage in batch file
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... the unique values. Here is the example program to store unique values in Java using

Ads