Java Count word occurrence and export it to excel file


 

Java Count word occurrence and export it to excel file

In this section, you will learn how to count word occurrence and export it to excel file.

In this section, you will learn how to count word occurrence and export it to excel file.

Java Count word occurrence and export it to excel file

Here is an example of scanning a text file in a local drive, and count the frequency of each word in the text file or you can say count the number or occurrence of each word and display the result the result into excel file in the table form.

Example:

import java.io.*;
import java.util.*;
import org.apache.poi.hssf.usermodel.HSSFSheet; 
import org.apache.poi.hssf.usermodel.HSSFWorkbook; 
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell; 

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 list1=new ArrayList();
ArrayList list2=new ArrayList();

ArrayList<Integer> list = new ArrayList<Integer>();
list.addAll(map.values());
Collections.sort(list);
int last = -1;
String filename="c:/count.xls" ;
HSSFWorkbook hwb=new HSSFWorkbook();
HSSFSheet sheet = hwb.createSheet("new sheet");

HSSFRow rowhead= sheet.createRow((short)0);
rowhead.createCell((short) 0).setCellValue("Keyword");
rowhead.createCell((short) 1).setCellValue("Count");
int k=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);
list1.add(s);
list2.add(Integer.toString(i));
}
}
}
for(int i=0;i<list1.size();i++){
HSSFRow row= sheet.createRow((short)k);
row.createCell((short) 0).setCellValue(list1.get(i).toString());
row.createCell((short) 1).setCellValue(list2.get(i).toString());
k++;
}
FileOutputStream fileOut = new FileOutputStream(filename);
hwb.write(fileOut);
fileOut.close();
System.out.println("Your excel file has been generated!");
}
catch(Exception e){
System.out.println(e);
}
} 
}

Ads