作業3:個人項目-詞頻統計


1.要求:實現一個控制台程序,給定一段英文字符串,統計其中各個英文單詞的出現頻率。

2.性能分析:

 

import java.util.ArrayList; 
import java.util.Collections; 
import java.util.Comparator; 
import java.util.HashMap; 
import java.util.List; 
import java.util.Map; 
import java.util.StringTokenizer; 
import java.util.Map.Entry; 
import java.util.Scanner;
   
   
   
public class 修改 {
    public static void main(String arg[]) {
        Map<String, Integer> map=
        //用於統計各單詞的個數
        new HashMap<String, Integer>();
        String sentence="Word is case insensitive, i.e. “file”, “FILE”"
                         + "and “File” are considered the same word."; 
        //大寫字母轉化為小寫
        sentence=sentence.toLowerCase();                     
        //將字符串分解成一個個的標記 
        StringTokenizer token=new StringTokenizer(sentence);  
        while (token.hasMoreTokens()) {
            //單詞用這些分隔符 分開
            String word=token.nextToken(", “”?.!:\"\"''\n"); 
            int count;   
            //HashMap不允許重復的key,用這個特性,去統計單詞的個數
            if (word.length()>=4) {
              if (map.containsKey(word)) {                        
                count=map.get(word); 
                //如果已有這個單詞則設置它的數量加1
                map.put(word, count + 1);                       
              } else {
                //如果沒有這個單詞則新填入數量為1 
                map.put(word, 1);
              }
            }                                              
        } 
            //調用函數並輸出      
            sort(map);                                           
    } 
 
public static void sort(Map<String, Integer> map) {
    List<Map.Entry<String, Integer>> infoIds =
    new ArrayList<Map.Entry<String, Integer>>(map.entrySet());  
    for ( int i = 0; i < infoIds.size(); i++) {
        Entry<String, Integer> id = infoIds.get(i);
        System.out.println(id.getKey() + ":" + id.getValue()); 
    } 
     
 
}
} 

  

  

下面是測試結果:

file:3
word:2
case:1
same:1
considered:1
insensitive:1

  當輸入的英文字符串為  Beware,beware!he'll cheat'ithout scruple,who can without fear.輸出為:

scruple:1
cheat:1
beware:2
without:1
ithout:1
fear:1

 總結:主要利用哈希函數的特性來統計單詞的個數,

      toLowerCase來確保不分大小寫 ,
      token.nextToken()來分離出英語單詞。

整體來說程序還是易於操作的。

github鏈接:https://github.com/Yizhongmeng/Mengzhongyi

性能
分析工具下載顯示電腦未安裝jdk。。。。。
 
 
        

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM