题目:https://leetcode.com/problems/word-frequency/
代码(github):https://github.com/illuz/leetcode
统计 word.txt 里的单词和频数,然后按频数从小到大排序输出。
- 用
awk统计单词个数。- 用
awk里的字典,循环统计每一行的第个单词。 - 处理完全部行后,再用
for (item in Dict) { #do someting# }把单词和频数输出来。
- 用
- 不过现在只是做好了统计,还要排序下。用管道
|把输出交给sort来排序sort -n把字符串转成数来比较。sort -r从小到大。sort -k 2把第二个字串当做 key。
English version:
- I should count the words. So I chose the
awkcommand.
- I use a dictionary in
awk. For every line I count every word in the dictionary. - After deal with all lines. At the
END, usefor (item in Dict) { #do someting# }to print every words and its frequency.
- Now the printed words are unsorted. Then I use a
|pipes and sort it bysort
sort -nmeans "compare according to string numerical value".sort -rmeans "reverse the result of comparisons".sort -k 2means "sort by the second word"