1. 程式人生 > >JAVA詞頻統計

JAVA詞頻統計

詞頻統計需求:

1.要求統計出一個檔案中的所有英文片語,以非英文字母為分隔符(這裡以空格為例)。

2.要求統計結果在控制檯輸出,並將統計的結果存入mysql資料庫和redis資料庫中。

3.要求以Map鍵值對的方式進行儲存,不區分大小寫(可以先將內容全部轉為大寫,或者全部轉為小寫實現不區分大小寫)

4.以字典的形式進行排序

   

詞頻統計:

package wordcount;

import redis.clients.jedis.Jedis;
import util.JDBCUnit;
import util.JedisPoolUtil;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

public class WordCount {
    public void displayWordCount(String fileName) {
        //以字元流的形式統計
        try {
            //讀取檔案
            FileReader fileReader = new FileReader(fileName);
            //使用流的方式讀取內容
            BufferedReader reader = new BufferedReader(fileReader);
            //使用TreeMap,它會自動將結果按照字典的順序排序
            TreeMap<String, Integer> tm = new TreeMap<String, Integer>();
            String readLine = null;
            while((readLine = reader.readLine()) != null){
                //將字母排序為小寫
                readLine = readLine.toLowerCase();
                //過濾出只含有字母的欄位
                String[] str = readLine.split("[\\s]+");
                //過濾掉所有的空格,“+”代表多個的意思。
                for (int i = 0; i < str.length; i++) {//迴圈統計出現次數
                    String word = str[i].trim();
                    if (tm.containsKey(word)) {
                        tm.put(word, tm.get(word) + 1);
                    } else {
                        tm.put(word, 1);
                    }
                }
            }

            //輸出我們想要的字串格式
            System.out.println("按字典序輸出為:");
            Iterator<Map.Entry<String, Integer>> it = tm.entrySet().iterator();
            //使用迭代器取值
            while(it.hasNext()) {
                Map.Entry<String, Integer> entry = it.next();
                //開始插入redis資料庫
                Jedis jedis = JedisPoolUtil.getJedis();
                jedis.hset("wordcount",entry.getKey(), String.valueOf(entry.getValue()));
                //開始插入mysql資料庫
                Connection conn = JDBCUnit.getConnection();
                String sql = "INSERT INTO wordcount(words,counts) VALUES(?,?)";
                PreparedStatement pst = conn.prepareStatement(sql);
                pst.setString(1,entry.getKey());
                pst.setString(2, String.valueOf(entry.getValue()));
                pst.executeUpdate();
                //將結果輸出到控制檯
                System.out.println(entry.getKey() + "\t" + entry.getValue());
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

JDBC連結工具類:

package util;

import java.sql.*;

public class JDBCUnit {
    private static final String NAME = "root";
    private static final String PASSWORD = "zxc";
    private static final String URL = "jdbc:mysql://localhost:3306/maven-wordcount?useUnicode=true&characterEncoding=UTF-8";
    static{
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * @return 返回資料庫的連線物件
     */
    public static Connection getConnection() {
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(URL, NAME, PASSWORD);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    /**
     * 關閉資源
     * @param connection 資料庫連線物件
     * @param statement SQL的執行物件
     */
    public static void release(Connection connection, Statement statement) {
        try {
            if (statement != null) {
                statement.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 關閉資源
     * @param connection 資料庫連線物件
     * @param statement SQL的執行物件
     * @param resultSet 結果集的物件
     */
    public static void release(Connection connection, Statement statement, ResultSet resultSet) {
        try {
            if (resultSet != null) {
                resultSet.close();
            }
            if (statement != null) {
                statement.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

Jedis連結工具類:

package util;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.io.InputStream;
import java.util.Properties;

public class JedisPoolUtil {
//    private static String host = "192.168.59.150";
//    private static int port = 6379;
    private static JedisPool jedisPool = null;
    static {
        //讀取配置檔案:使用getClassLoader()類載入器的getResourceAsStream()獲取流的方法,獲取配置檔案內容
        //每個類都有他的載入器,JedisPoolUtil.class只要 這裡 是個類就可以,他就可以呼叫 類載入器 將檔案上傳到記憶體
        //使用類就是為了使用類載入器
        InputStream inputStream = JedisPoolUtil.class.getClassLoader().getResourceAsStream("redisDB.properties");
        //Properties專門讀取.properties檔案的類
        Properties properties = new Properties();
        try {
            properties.load(inputStream);
        } catch (Exception e) {
            System.out.println("配置檔案讀取失敗!");
        }
        String host = properties.getProperty("redis.host");
        //Integer.parseInt()這個方法時將字串讀取為一個整數
        Integer Max_Total = Integer.parseInt(properties.getProperty("redis.MaxTotal"));
        Integer Max_Idle = Integer.parseInt(properties.getProperty("redis.MaxIdle"));
        Integer Min_Idle = Integer.parseInt(properties.getProperty("redis.MinIdle"));
        Integer port = Integer.parseInt(properties.getProperty("redis.port"));
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        //設定預設連結數
        jedisPoolConfig.setMaxTotal(Max_Total);
        //設定最大空閒數
        jedisPoolConfig.setMaxIdle(Max_Idle);
        //設定最小空閒數
        jedisPoolConfig.setMinIdle(Min_Idle);
        //獲取連結池物件
        jedisPool = new JedisPool(jedisPoolConfig, host, port);
//        System.out.println(host+"\n"+port+"\n"+Max_Total+"\n"+Max_Idle+"\n"+Min_Idle);
    }

    public static Jedis getJedis() {
        //獲取資料庫操作物件
        return jedisPool.getResource();
    }

    public static void release(Jedis jedis) {
        if (jedis != null) {
            //釋放資源
            jedis.close();
        }
    }
}

redisDB配置檔案(properties檔案):

redis.port=6379
redis.host=192.168.59.150
redis.MaxTotal=10
redis.MaxIdle=8
redis.MinIdle=8

測試類:

package wordcount;

public class Main {
    public static void main(String[] args) {
        String line = "C:\\Users\\Super\\Desktop\\123.txt";
        //過濾掉首尾空字串
        String fileName = line.trim();
        WordCount wc = new WordCount();
        wc.displayWordCount(fileName);
    }
}

ps:如果不需要儲存到資料庫操作這個操作,將對應的資料庫工具和方法刪掉就好,emmm

THE END。。。