Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Answers Viewqa Java-Beginners tO FIND UNIQUE WORDS IN A FILE USING HASHMAP
Login         

View Questions and Answers by Category

Advertisements


 
Have Programming Question? Ask it here!
 
 
 


daksesh
tO FIND UNIQUE WORDS IN A FILE USING HASHMAP
1 Answer(s)      2 years and 5 months ago
Posted in : Java Beginners


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

}

}


Advertisement
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
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
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
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
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
HashMap
HashMap  How to work hashmap and hashset internally
hashmap
hashmap  write a program that shows the use of Hashmap class
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
HASHMAP
HASHMAP  HI CAN WE ADD PRIMITIVE DATA TYPE IN HASHMAP IN JAVA 1.5 VERSION . THANKS KALINS NAIK   Java HashMap Example
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
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
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
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
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
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
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 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
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
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
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
Java hashmap, hashtable
Java hashmap, hashtable  When are you using hashmap and hashtable
HashMap - Struts
HashMap  Can you please get me an example code for using HashMap in Jsp and what for what purpose it is used
Advertisements
 

 

 

DMCA.com