Pipes實現(xiàn)LeetCode(192.單詞頻率)
[LeetCode] 192.Word Frequency 單詞頻率
Write a bash script to calculate the frequency of each word in a text file words.txt.
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:
the day is sunny the the
the sunny is is
Your script should output the following, sorted by descending frequency:
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.
Could you write it in one-line using Unix pipes?
這道題給了我們一個文本文件,讓我們統(tǒng)計里面單詞出現(xiàn)的個數(shù),提示中讓我們用管道Pipes來做,在之前那道Tenth Line中,我們使用過管道命令。提示中讓我們用管道連接各種命令,然后一行搞定,那么我們先來看第一種解法,乍一看啥都不明白,咋辦?沒關(guān)系,容我慢慢來講解。首先用的關(guān)鍵字是grep命令,該命令一種強(qiáng)大的文本搜索工具,它能使用正則表達(dá)式搜索文本,并把匹配的行打印出來。后面緊跟的-oE '[a-z]+'參數(shù)表示原文本內(nèi)容變成一個單詞一行的存儲方式,于是此時文本的內(nèi)容就變成了:
the
day
is
sunny
the
the
the
sunny
is
下面的sort命令就是用來排序的。排完序的結(jié)果為:
day
is
is
is
sunny
sunny
the
the
the
the
后面的uniq命令是表示去除重復(fù)行命令,后面的參數(shù)-c表示在每行前加上表示相應(yīng)行目出現(xiàn)次數(shù)的前綴編號,得到結(jié)果如下:
1 day
3 is
2 sunny
4 the
然后我們再sort一下,后面的參數(shù)-nr表示按數(shù)值進(jìn)行降序排列,得到結(jié)果:
4 the
3 is
2 sunny
1 day
而最后的awk命令就是將結(jié)果輸出,兩列顛倒位置即可:
解法一:
grep -oE '[a-z]+' words.txt | sort | uniq -c | sort -nr | awk '{print $2" "$1}'
下面這種方法用的關(guān)鍵字是tr命令,該命令主要用來進(jìn)行字符替換或者大小寫替換。后面緊跟的-s參數(shù)表示如果發(fā)現(xiàn)連續(xù)的字符,就把它們縮減為1個,而后面的‘ '和‘\n'就是空格和回車,意思是把所有的空格都換成回車,那么第一段命令tr -s ' ' '\n' < words.txt 就好理解了,將單詞之間的空格都換成回車,跟上面的第一段實現(xiàn)的作用相同,后面就完全一樣了,參見上面的講解:
解法二:
tr -s ' ' '\n' < words.txt | sort | uniq -c | sort -nr | awk '{print $2, $1}'
下面這種方法就沒有用管道命令進(jìn)行一行寫法了,而是使用了強(qiáng)大的文本分析工具awk進(jìn)行寫類C的代碼來實現(xiàn),這種寫法在之前的那道Transpose File已經(jīng)講解過了,這里就不多說了,最后要注意的是sort命令的參數(shù)-nr -k 2表示按第二列的降序數(shù)值排列:
解法三:
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
到此這篇關(guān)于Pipes實現(xiàn)LeetCode(192.單詞頻率)的文章就介紹到這了,更多相關(guān)Pipes實現(xiàn)單詞頻率內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C語言指針變量作為函數(shù)參數(shù)的實現(xiàn)步驟詳解
這篇文章主要介紹了C語言指針變量作為函數(shù)參數(shù)的實現(xiàn)步驟,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2023-02-02