[LeetCode] Word Frequency 單詞頻率

 

Write a bash script to calculate the frequency of each word in a text file words.txt.html

For simplicity sake, you may assume:正則表達式

  • words.txt contains only lowercase characters and space ' ' characters.
  • Each word must consist of lowercase characters only.
  • Words are separated by one or more whitespace characters.

For example, assume that words.txt has the following content:shell

the day is sunny the the
the sunny is is

Your script should output the following, sorted by descending frequency:bash

the 4
is 3
sunny 2
day 1

Note:
Don't worry about handling ties, it is guaranteed that each word's frequency count is unique. session

[show hint]工具

Hint:
Could you write it in one-line using Unix pipes?

 

這道題給了咱們一個文本文件,讓咱們統計裏面單詞出現的個數,提示中讓咱們用管道Pipes來作,在以前那道Tenth Line中,咱們使用過管道命令,管道命令的講解請參見這個帖子。提示中讓咱們用管道鏈接各類命令,而後一行搞定,那麼咱們先來看第一種解法,乍一看啥都不明白,咋辦?不要緊,容我慢慢來說解。首先用的關鍵字是grep命令,該命令一種強大的文本搜索工具,它能使用正則表達式搜索文本,並把匹配的行打印出來,詳解請參見這個帖子。後面緊跟的-oE '[a-z]+'參數表示原文本內容變成一個單詞一行的存儲方式,因而此時文本的內容就變成了:post

the
day
is
sunny
the
the
the
sunny
isurl

下面的sort命令就是用來排序的,參見這個帖子。排完序的結果爲:spa

day
is
is
is
sunny
sunny
the
the
the
the.net

後面的uniq命令是表示去除重複行命令(參見這個帖子),後面的參數-c表示在每行前加上表示相應行目出現次數的前綴編號,獲得結果以下:

   1 day
   3 is
   2 sunny
   4 the

而後咱們再sort一下,後面的參數-nr表示按數值進行降序排列,獲得結果:

   4 the
   3 is
   2 sunny
   1 day 

而最後的awk命令就是將結果輸出,兩列顛倒位置便可:

 

解法一:

grep -oE '[a-z]+' words.txt | sort | uniq -c | sort -nr | awk '{print $2" "$1}' 

 

 

下面這種方法用的關鍵字是tr命令,該命令主要用來進行字符替換或者大小寫替換,詳解請參見這個帖子。後面緊跟的-s參數表示若是發現連續的字符,就把它們縮減爲1個,然後面的‘ ’和‘\n'就是空格和回車,意思是把全部的空格都換成回車,那麼第一段命令tr -s ' ' '\n' < words.txt 就好理解了,將單詞之間的空格都換成回車,跟上面的第一段實現的做用相同,後面就徹底同樣了,參見上面的講解:

 

解法二:

tr -s ' ' '\n' < words.txt | sort | uniq -c | sort -nr | awk '{print $2, $1}'

 

 

下面這種方法就沒有用管道命令進行一行寫法了,而是使用了強大的文本分析工具awk進行寫類C的代碼來實現,這種寫法在以前的那道Transpose File已經講解過了,這裏就很少說了,最後要注意的是sort命令的參數-nr -k 2表示按第二列的降序數值排列:

 

解法三:

awk '{
    for (i = 1; i <= NF; ++i) ++s[$i];
} END {
    for (i in s) print i, s[i];
}' words.txt | sort -nr -k 2

 

參考資料:

https://leetcode.com/discuss/33353/my-accepted-answer-using-tr-sort-uniq-and-awk

https://leetcode.com/discuss/46976/my-ac-solution-one-pipe-command-but-cost-20ms

https://leetcode.com/discuss/29001/solution-using-awk-and-pipes-with-explaination

 

LeetCode All in One 題目講解彙總(持續更新中...)

相關文章
相關標籤/搜索