Mlog9: LeetCode -- 統(tǒng)計(jì)詞頻

image

文章目錄:

  1. 題目要求--分析
  2. 具體實(shí)現(xiàn)--動(dòng)手
  3. 源碼分析--知其然,知其所以然
  4. 優(yōu)化--創(chuàng)新
  5. 總結(jié)

1. 題目要求--分析


寫一個(gè)腳本以統(tǒng)計(jì)一個(gè)文本文件 words.txt 中每個(gè)單詞出現(xiàn)的頻率鸳粉。
為了簡(jiǎn)單起見(jiàn)谴餐,你可以假設(shè):
words.txt只包括小寫字母和 ' ' ;
每個(gè)單詞只由小寫字母組成。
單詞間由一個(gè)或多個(gè)空格字符分隔加袋。
示例:
假設(shè) words.txt 內(nèi)容如下:
the day is sunny the the the sunny is is
你的腳本應(yīng)當(dāng)輸出(以詞頻降序排列):
the 4
is 3
sunny 2
day 1

2. 具體實(shí)現(xiàn)--動(dòng)手


1.輸入哥艇,讀取文件谐腰,使用 FileInputStream显设、BufferedReader讀取文件框弛;
2.分割字符串,采用StringTokenizer進(jìn)行字符分割捕捂;
3.用 HashMap 保存統(tǒng)計(jì)數(shù)據(jù)瑟枫;
4.統(tǒng)計(jì)詞頻斗搞,降序排序輸出,采用Comparator用來(lái)實(shí)現(xiàn)按value排序
5.輸出

package algorithm;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
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;

public class WordFrequency {

    public static void main(String[] args) {

        long startTime=System.nanoTime();   //獲取開(kāi)始時(shí)間

        String string = "";
        Map<String, Integer> map = new HashMap<String,Integer>();
        try {
            //[1] 讀取 2.txt 文本
            FileInputStream fis = new FileInputStream("/Users/sweetgirl/Documents/MyCode/2.txt");
            BufferedReader br = new BufferedReader(new InputStreamReader(fis));
            String temp = "";
            try {
                while((temp = br.readLine()) != null) {
                    string = string + temp;
                }
            } catch (IOException e) {
                // TODO: handle exception
                e.printStackTrace();
            }

        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

        //[2] 分割字符串
        StringTokenizer st = new StringTokenizer(string); //用于切分字符串
        int count;
        String word;
        while(st.hasMoreTokens()) {
             word = st.nextToken(",?.!:\"\"' '\n");
             if (map.containsKey(word)) {
                //[3] HashMap 保存數(shù)據(jù)
                 count = map.get(word);
                 map.put(word, count + 1);

            }else {
                map.put(word, 1);
            }
            }

         //[4] 排序
        Comparator<Map.Entry<String, Integer>> valueComparator = new Comparator<Map.Entry<String,Integer>>() {
        public int compare(Map.Entry<String, Integer> o1,Map.Entry<String, Integer> o2) {
            return o2.getValue()-o1.getValue();
        }
        };
        //[5] 輸出結(jié)果
        List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String,Integer>>(map.entrySet());
        Collections.sort(list,valueComparator);

        System.out.println("---------------------map 按照 value 降序排序----------");
        for(Map.Entry<String, Integer> entry:list) {
            System.out.println(entry.getKey() + ":"+ entry.getValue());
        }

        long endTime=System.nanoTime(); //獲取結(jié)束時(shí)間
        System.out.println("程序運(yùn)行時(shí)間: "+(endTime-startTime)+"ns");

    }

}

測(cè)試文本:

Photo sphere panoramic camera function; keyboard gesture input function; improved lock screen function, including support for desktop pendant and direct opening camera function in lock screen state; expandable notification, allowing users to directly open the application; Gmail mail zoom display; Daydream screen saver Program; the user can zoom in on the entire display three times, and can also rotate and zoom display with two fingers, as well as voice output and gesture mode navigation designed for blind users; support Miracast wireless display sharing function; Google Now is now available Allow users to use Gamail as a new source of data, such as improved flight tracking, hotel and restaurant reservations, and music and movie recommendations.Photo sphere panoramic camera function; keyboard gesture input function; improved lock screen function, including support for desktop pendant and direct opening camera function in lock screen state; expandable notification, allowing users to directly open the application; Gmail mail zoom display; Daydream screen saver Program; the user can zoom in on the entire display three times, and can also rotate and zoom display with two fingers, as well as voice output and gesture mode navigation designed for blind users; support Miracast wireless display sharing function.

測(cè)試結(jié)果:

---------------------map 按照 value 降序排序----------
and:11
screen:6
as:6
display:6
zoom:6
the:6
function:5
function;:5
lock:4
in:4
support:4
for:4
gesture:4
can:4
camera:4
improved:3
users:3
to:3
voice:2
rotate:2
mail:2
state;:2
panoramic:2
Photo:2
entire:2
fingers:2
three:2
output:2
mode:2
notification:2
navigation:2
saver:2
users;:2
directly:2
Miracast:2
including:2
sharing:2
input:2
application;:2
Daydream:2
blind:2
display;:2
expandable:2
direct:2
pendant:2
two:2
times:2
desktop:2
sphere:2
designed:2
on:2
keyboard:2
Gmail:2
also:2
allowing:2
opening:2
with:2
Program;:2
well:2
wireless:2
user:2
open:2
Gamail:1
data:1
movie:1
use:1
available:1
source:1
tracking:1
recommendations:1
music:1
Google:1
new:1
is:1
Now:1
flight:1
now:1
of:1
hotel:1
a:1
restaurant:1
Allow:1
such:1
reservations:1
程序運(yùn)行時(shí)間: 13034950ns

3. 源碼分析--知其然慷妙,知其所以然

Hashmap [1] 存值

1  public static void main(String[] args) {
2 
3          HashMap<String, Integer> map=new HashMap<>();
4          System.out.println(map.put("1", 1));//null
5          System.out.println(map.put("1", 2));//1
6      }

Hashmap [2] 取值

1 public static void main(String[] args) {
2         HashMap<String, Integer> map=new HashMap<>();
3         map.put("DEMO", 1);
4         System.out.println(map.get("1"));//null
5         System.out.println(map.get("DEMO"));//1
6     }

image

4. 優(yōu)化--創(chuàng)新

分割字符串 方法二:

package algorithm;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
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;

public class WordFrequency {

    public static void main(String[] args) {

        long startTime=System.nanoTime();   //獲取開(kāi)始時(shí)間

        String string = "";
        Map<String, Integer> map = new HashMap<String,Integer>();
        try {
            //[1] 讀取 2.txt 文本
            FileInputStream fis = new FileInputStream("/Users/sweetgirl/Documents/MyCode/2.txt");
            BufferedReader br = new BufferedReader(new InputStreamReader(fis));
            String temp = "";
            try {
                while((temp = br.readLine()) != null) {
                    string = string + temp;
                }
            } catch (IOException e) {
                // TODO: handle exception
                e.printStackTrace();
            }

        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

        //[2] 分割字符串

         String[] spit = string.split(" ");
         for(int i = 0; i < spit.length; i++) {
            if (map.get(spit[i]) == null) {
                map.put(spit[i], 1);
            }else {
                //[3] HashMap 保存數(shù)據(jù)
                int frequency = map.get(spit[i]);
                map.put(spit[i], ++frequency);
            }
        }

         //[4] 排序
        Comparator<Map.Entry<String, Integer>> valueComparator = new Comparator<Map.Entry<String,Integer>>() {
        public int compare(Map.Entry<String, Integer> o1,Map.Entry<String, Integer> o2) {
            return o2.getValue()-o1.getValue();
        }
        };

        List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String,Integer>>(map.entrySet());
        Collections.sort(list,valueComparator);

        System.out.println("---------------------map 按照 value 降序排序----------");
        for(Map.Entry<String, Integer> entry:list) {
            System.out.println(entry.getKey() + ":"+ entry.getValue());
        }

        long endTime=System.nanoTime(); //獲取結(jié)束時(shí)間
        System.out.println("程序運(yùn)行時(shí)間: "+(endTime-startTime)+"ns");

    }

}

測(cè)試文本:
同上
測(cè)試結(jié)果:

---------------------map 按照 value 降序排序----------
and:11
screen:6
as:6
display:6
zoom:6
the:6
function;:5
lock:4
in:4
support:4
for:4
gesture:4
can:4
camera:4
improved:3
users:3
to:3
voice:2
rotate:2
mail:2
state;:2
panoramic:2
entire:2
three:2
output:2
mode:2
navigation:2
function:2
saver:2
users;:2
directly:2
Miracast:2
including:2
sharing:2
input:2
application;:2
Daydream:2
blind:2
display;:2
expandable:2
direct:2
times,:2
function,:2
pendant:2
two:2
desktop:2
sphere:2
designed:2
on:2
keyboard:2
Gmail:2
also:2
allowing:2
opening:2
with:2
fingers,:2
notification,:2
Program;:2
well:2
wireless:2
user:2
open:2
Gamail:1
movie:1
use:1
available:1
Photo:1
source:1
music:1
Google:1
new:1
is:1
Now:1
flight:1
function.:1
now:1
of:1
hotel:1
tracking,:1
a:1
recommendations.Photo:1
restaurant:1
data,:1
Allow:1
such:1
reservations,:1
程序運(yùn)行時(shí)間: 9878808ns

5. 總結(jié)

當(dāng)文本為 1 KB 時(shí)僻焚,方法一 (使用 StringTokenizer )程序運(yùn)行時(shí)間: 13034950ns;方法二 (使用 spit )程序運(yùn)行時(shí)間: 9878808ns .
StringTokenizer > spit

當(dāng)文本為 24 KB 時(shí)膝擂,方法一 (使用 StringTokenizer )程序運(yùn)行時(shí)間: 25411294ns虑啤;方法二 (使用 spit )程序運(yùn)行時(shí)間: 28782200ns .
StringTokenizer < spit

綜上可知,當(dāng)你需要統(tǒng)計(jì)詞頻的文本較大時(shí)猿挚,例如一本長(zhǎng)篇小說(shuō)咐旧,那么 StringTokenizer 的效率更高。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末绩蜻,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子室埋,更是在濱河造成了極大的恐慌办绝,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,548評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件姚淆,死亡現(xiàn)場(chǎng)離奇詭異孕蝉,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)腌逢,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,497評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門降淮,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人搏讶,你說(shuō)我怎么就攤上這事佳鳖。” “怎么了媒惕?”我有些...
    開(kāi)封第一講書(shū)人閱讀 167,990評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵系吩,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我妒蔚,道長(zhǎng)穿挨,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 59,618評(píng)論 1 296
  • 正文 為了忘掉前任肴盏,我火速辦了婚禮科盛,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘菜皂。我一直安慰自己贞绵,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,618評(píng)論 6 397
  • 文/花漫 我一把揭開(kāi)白布幌墓。 她就那樣靜靜地躺著但壮,像睡著了一般冀泻。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上蜡饵,一...
    開(kāi)封第一講書(shū)人閱讀 52,246評(píng)論 1 308
  • 那天弹渔,我揣著相機(jī)與錄音,去河邊找鬼溯祸。 笑死肢专,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的焦辅。 我是一名探鬼主播博杖,決...
    沈念sama閱讀 40,819評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼筷登!你這毒婦竟也來(lái)了剃根?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 39,725評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤前方,失蹤者是張志新(化名)和其女友劉穎狈醉,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體惠险,經(jīng)...
    沈念sama閱讀 46,268評(píng)論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡苗傅,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,356評(píng)論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了班巩。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片渣慕。...
    茶點(diǎn)故事閱讀 40,488評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖抱慌,靈堂內(nèi)的尸體忽然破棺而出逊桦,到底是詐尸還是另有隱情,我是刑警寧澤遥缕,帶...
    沈念sama閱讀 36,181評(píng)論 5 350
  • 正文 年R本政府宣布卫袒,位于F島的核電站,受9級(jí)特大地震影響单匣,放射性物質(zhì)發(fā)生泄漏夕凝。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,862評(píng)論 3 333
  • 文/蒙蒙 一户秤、第九天 我趴在偏房一處隱蔽的房頂上張望码秉。 院中可真熱鬧,春花似錦鸡号、人聲如沸转砖。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,331評(píng)論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)府蔗。三九已至晋控,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間姓赤,已是汗流浹背赡译。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,445評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留不铆,地道東北人蝌焚。 一個(gè)月前我還...
    沈念sama閱讀 48,897評(píng)論 3 376
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像誓斥,于是被迫代替她去往敵國(guó)和親只洒。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,500評(píng)論 2 359

推薦閱讀更多精彩內(nèi)容