?LeetCode刷題實戰(zhàn)192:統(tǒng)計詞頻
Write a bash script to calculate the frequency of each word in a text file words.txt.
題意
words.txt只包括小寫字母和 ' ' 。
每個單詞只由小寫字母組成。
單詞間由一個或多個空格字符分隔。
示例
假設(shè) words.txt 內(nèi)容如下:
the day is?sunny the the
the sunny is?is
你的腳本應(yīng)當輸出(以詞頻降序排列):
the 4
is?3
sunny 2
day 1
說明:
不要擔心詞頻相同的單詞的排序問題,每個單詞出現(xiàn)的頻率都是唯一的。
你可以使用一行 Unix pipes 實現(xiàn)嗎?
解題
思路:cat+tr+sort+uniq+sort+awk
cat?words.txt | tr?-s ' '?'\n'?| sort?| uniq -c?| sort?-r | awk '{ print $2, $1 }'
評論
圖片
表情
