Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package cirno.task1;
- import java.io.*;
- import java.util.*;
- /**
- * Created by IntelliJ IDEA.
- * User: cirno
- * Date: 2/19/11
- * Time: 7:18 PM
- * To change this template use File | Settings | File Templates.
- */
- class Cmp implements Comparator<Pair> {
- public int compare(Pair a, Pair b) {
- return b.getValue() - a.getValue();
- }
- }
- class Pair {
- private String key;
- private int value;
- public Pair(String a, int b) {
- key = a;
- value = b;
- }
- public int getValue() {
- return value;
- }
- public String getKey() {
- return key;
- }
- }
- public class WordCounter {
- private static HashMap<String, Integer> map = new HashMap<String, Integer>();
- private static int wNum = 0;
- public static void main(String args[]) {
- if (args.length > 0) {
- doAnything(args[0]);
- } else {
- System.out.println("Specify the file");
- }
- }
- static void printTable() {
- List<Pair> lst = new ArrayList<Pair>();
- for(Map.Entry<String, Integer> entry : map.entrySet()) {
- lst.add(new Pair(entry.getKey(), entry.getValue()));
- }
- Collections.sort(lst, new Cmp());
- for(Pair entry : lst) {
- System.out.println(entry.getKey() + ";" + entry.getValue() + ";" + (double)entry.getValue() / wNum);
- }
- }
- static void doAnything(String fileName) {
- FileInputStream stream = null;
- try {
- stream = new FileInputStream(fileName);
- byte[] buf = new byte[stream.available()];
- stream.read(buf);
- String str = new String(buf);
- String [] strArr = str.split("[^a-zA-Z0-9]");
- for(String s:strArr) {
- map.put(s, 1 + (map.containsKey(s) ? map.get(s) : 0));
- wNum++;
- }
- printTable();
- }
- catch (IOException e) {
- System.err.println("Error while reading file: " + e.getLocalizedMessage());
- }
- finally {
- if (null != stream) {
- try {
- stream.close();
- }
- catch (IOException e) {
- e.printStackTrace(System.err);
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement