Skip to content

Instantly share code, notes, and snippets.

@mattman
Created April 27, 2009 13:21
Show Gist options
  • Save mattman/102479 to your computer and use it in GitHub Desktop.
Save mattman/102479 to your computer and use it in GitHub Desktop.
/**
* Write a description of class TextAnalyser here.
*
* @author Matt Didcoe
* @version 0.1
*/
import java.lang.*;
import java.util.*;
public class TextAnalyser {
// instance variables - replace the example below with your own
private String text;
private int totalAnalysed;
private int textLength;
private char[] charArray;
private int count;
private Map<Character, Integer> m = new HashMap<Character, Integer>();
private HashMap map = new LinkedHashMap();
private String workable;
/**
* Constructor for objects of class TextAnalyser
*/
public TextAnalyser(String txt) {
// initialise instance variables
text = txt.toLowerCase();
textLength = text.length();
analyse(txt);
}
public TextAnalyser(){
totalAnalysed = 0;
}
public void analyse(String s) {
if(text != null) {
makeArray(text);
} else {
text = s.toLowerCase();
textLength = text.length();
makeArray(s);
}
}
public int charsAnalysed() {
return totalAnalysed;
}
public int frequency(char c) {
int occurence=0;
for (int i = 0; i < charArray.length; i++) {
if (charArray[i] == Character.toLowerCase(c))
occurence++;
}
return occurence;
}
public double percentage(char c) {
if(totalAnalysed != 0)
return 100*(new Double(frequency(c)) / new Double(totalAnalysed));
else
return 0.0;
}
public char mostFrequent() {
if(totalAnalysed == 0){
return '?';
} else {
count_letters();
List keyList = Arrays.asList(map.keySet().toArray());
return (keyList.get(keyList.size()-1)).toString().charAt(0);
}
}
public void clear() {
totalAnalysed = 0;
}
private void makeArray(String str){
workable = str.replaceAll("[^a-zA-Z]","");
char[] arr = workable.toLowerCase().toCharArray();
totalAnalysed += arr.length;
charArray = arr;
}
private void count_letters() {
char[] ca = new char[]{'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
int [] CounterArrays = new int [ca.length];
// pass thru every character in the line
for (int i = 0; i < charArray.length; i++) {
// test for letter of the alphabet
for(int j = 0; j < ca.length; j++) {
// if match
if(charArray[i] == ca[j]) {
CounterArrays[j]++;
break;
}
}
}
// print the result
for(int z = 1; z < CounterArrays.length; z++) {
if (CounterArrays[z] != 0) {
m.put(ca[z], CounterArrays[z]);
}
}
List mapKeys = new ArrayList(m.keySet());
List mapValues = new ArrayList(m.values());
TreeSet sortedSet = new TreeSet(mapValues);
Object[] sortedArray = sortedSet.toArray();
int size = sortedArray.length;
for (int i=0; i<size; i++) {
map.put(mapKeys.get(mapValues.indexOf(sortedArray[i])),sortedArray[i]);
}
}
public void stupid() {
System.out.println(workable);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment