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



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

Have Programming Question? Ask it here!
 
 
 


daksesh
tO FIND UNIQUE WORDS IN A FILE USING HASHMAP
1 Answer(s)      2 years and 4 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
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
HashMap
HashMap  How to work hashmap and hashset internally
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
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  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 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
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
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
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
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
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
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
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 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 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
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
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  
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
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
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
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
How to get Keys and Values from HashMap in Java?
How to get Keys and Values from HashMap in Java? Example program of iterating through HashMap In this tutorial I will explain you how you can iterate through HashMap using the entrySet() method of HashMap class. You will be able
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
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
Example - Read Words
Java Notes: Example - Read Words The program below reads a text file.../ReadWordsGUI.java // Purpose: Read a file and display all words in it. // Author... // Purpose: Read a file and display all words in it. // Author : Fred Swartz
Name unique
. In other words, value for the name should be unique
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
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
Java Hashmap Iterator
Java HashMap Iterator is a collection class. It implements the Map interface. It keeps the data in the key and value form. Java HashMap has no iterator.... Set's all elements can be traversed by the Iterator. Java Hashmap Iterator
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
Error 500-Server are not find the jar file in the program of upload the file - JSP-Servlet
Error 500-Server are not find the jar file in the program of upload... a program to upload a file.I include the commons-fileupload-1.2.1.jar file in lib...); // Create a new file upload handler System.out.println(isMultipart); DiskFileUpload
Differences between HashMap and Hashtable?
Differences between HashMap and Hashtable?  Differences between HashMap and Hashtable
Unique field
Unique field  I have created a form where I have a textbox and a button. When I write something in the textbox and click on submit,it should go... in the textbox is not unique. How should I proceed with it? Plz help
Advertisements
 

 

 

DMCA.com