[Leetcode] 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.


題目大意: 計算每一個單詞出現的頻率,文件裏面包含的是大於等於一個空白字符和小寫字母
解題思路: 大體就是對文件的內容進行搜索,排序和統計,那麼大體的命令就是grep,sort和uniq的命令來完成

代碼如下
grep -Eo "[a-z]*" words.txt|sort -k1|uniq -c|sort -r|awk '{print $2" "$1}'

網上也有其他的答案
cat words.txt \
| tr -s ' ' '\n' \
| awk '{ words[$1]++ } END { for (key in words) print key, words[key] }' \
| sort -rn -k2


總體來說大同小異,擴展一下思路也是一個好事。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章