LeetCode 192
01 题目描述
写一个 bash 脚本以统计一个文本文件 words.txt 中每个单词出现的频率。为了简单起见,你可以假设:
1. words.txt只包括小写字母和 ' ' 。
2. 每个单词只由小写字母组成。
3. 单词间由一个或多个空格字符分隔。
02(words.txt)文件内容
the day is sunny the thethe sunny is is
03 输出(以词频降序排列):
the 4
is 3
sunny 2
day 1
04 解析
对于words.txt文件进行词频统计,首先要做的事情就是把words.txt文件当中的每一个单词分割出来,分割出每一个单词可以使用以下两种方式:
使用awk命令:
[root@localhost ~]# awk '{for(i=1;i<=NF;i++){print $i}}' words.txt
the
day
is
sunny
the
the
the
sunny
is
is
其中NF表示当前记录的字段数(即列数)
$i 文件中每行以间隔符号分割的不同字段
如果对awk命令不熟悉,可以参考之前分享的一篇文章学习:
使用xargs命令:
[root@localhost ~]# cat words.txt | xargs -n1
the
day
is
sunny
the
the
the
sunny
is
is
[root@localhost ~]# cat words.txt | xargs -n2
the day
is sunny
the the
the sunny
is is
xargs命令是用于给其他命令传递参数的一个过滤器,也是组合多个命令的一个工具。
-n选项,指定 输出时每行输出的列数
当我们将words.txt文件中的所有单词都分割出来之后,就可以统计这些单词当中每一个单词出现的次数了。
我们仅考虑使用awk命令来完成这个任务的话很简单,在进行分割的过程中直接用一个关联数组直接保存每一个单词出现的次数,关于关联数组的更多内容可以阅读:SHELL编程之变量与四则运算,此处我们可以暂时将关联数组理解为一个字典,关键字为单词,值为单词出现的次数(这样理解只是一种通俗的说法)
[root@localhost ~]# awk '{for(i=1;i<=NF;i++){a