简体   繁体   中英

count word frequency in multiple files/documents in java

I want to count word frequency to multiple files/documents in java.

eg

a1 = {aaa,aaa,aaa,bbb}
a2 = {aaa, aaa, hhh}
a3 = {aaa, hhh, bbb, bbb}

So, I want to count word frequency for every file:

for a1 file {aaa = 3, bbb = 1}
for a2 file {aaa = 2, hhh = 1}
for a3 file {aaa = 1, hhh = 1, bbb =2}

I have a method that reads the words from file and then, stores <wordname, worcount> in a LinkedHashMap . Nevertheless, this it will count the frequency of a specific word for all files, but I want to count word frequency separately for every file.

Does anybody have any solution?


Then, I wrote this:

Set mapset = fileToWordCount.keySet();           

for(Object filenameFromMap: mapset){
      System.out.println("FILENAME::"+filenameFromMap);
}

But, it doesn't print anything.

You can create another Map that would map file name to the LinkedHashMap with word counts. So you would have something like this:

Map<String, LinkedHashMap<String, Integer>> fileToWordCount = new HashMap<String, LinkedHashMap<String, Integer>();

Then, for each file you would build your word frequency as usual and add values to the map above this way:

fileToWordCount.put(file.getPath(), wordCountMap);

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

public class file1{
 public static void main(String[] args) throws Exception{
HashMap<String,Integer> words_fre = new HashMap<String,Integer>();
HashSet<String> words = new HashSet<String>();
try{  

       File folder = new File("</file path>");
       File[] listOfFiles = folder.listFiles();

       BufferedReader bufferedReader=null;
       FileInputStream inputfilename=null;
       BufferedWriter out= new BufferedWriter(new OutputStreamWriter(new FileOutputStream("outfilename.txt",false), "UTF-8"));

        for(File file : listOfFiles){           
           inputfilename= new FileInputStream(file); 
           /*System.out.println(file); */    
           bufferedReader= new BufferedReader(new InputStreamReader(inputfilename, "UTF-8"));


             String s;
             while((s = bufferedReader.readLine()) != null){
               /*System.out.println(line);*/
                  s = s.replaceAll("\\<.*?>"," ");
                    if(s.contains("॥") || s.contains(":")|| s.contains("।")|| 
                     s.contains(",")|| s.contains("!")|| s.contains("?")){
                         s=s.replace("॥"," ");
                         s=s.replace(":"," ");
                         s=s.replace("।"," ");
                         s=s.replace(","," ");
                         s=s.replace("!"," ");
                         s=s.replace("?"," ");
                       }                                                   
                  StringTokenizer st = new StringTokenizer(s," ");
                  while (st.hasMoreTokens()) {         
                  /*out.write(st.nextToken()+"\n");*/
                  String str=(st.nextToken()).toString();
                  words.add(str);
                }
                for(String str : words){
                  if(words_fre.containsKey(str)){  
                           int a = words_fre.get(str);  
                           words_fre.put(str,a+1);             
                  }else{  
                      words_fre.put(str,1);/*uwords++;//unique words count */  
                  }                      
                }
                words.clear(); 

                  /*out.write("\n");
                  out.close();*/

             }             
             Object[] key =   words_fre.keySet().toArray();   
                  Arrays.sort(key);  
                  for (int i = 0; i < key.length; i++) {  
                    //System.out.println(key[i]+"= "+words_fre.get(key[i]));
                 out.write(key[i]+" : "+words_fre.get(key[i]) +"\n");
               }


         }

            out.close();
            bufferedReader.close();

      }catch(FileNotFoundException ex){
         System.out.println("Error in reading line");
        }catch(IOException ex){
            /*System.out.println("Error in reading line"+fileReader );*/
            ex.printStackTrace();
           }

} }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM