Shell练习:统计词频

写一个 bash 脚本以统计一个文本文件 words.txt 中每个单词出现的频率。

为了简单起见,你可以假设:

words.txt只包括小写字母和 ' ' 。
每个单词只由小写字母组成。
单词间由一个或多个空格字符分隔。
示例:

假设 words.txt 内容如下:

the day is sunny the the
the sunny is is
你的脚本应当输出(以词频降序排列):

the 4
is 3
sunny 2
day 1
说明:
不要担心词频相同的单词的排序问题,每个单词出现的频率都是唯一的。
你可以使用一行 Unix pipes 实现吗?

方法1

# 换行
# xargs -n用于多行输出(n后面的数字:表示每行有几个字符)
☁  work  cat words.txt | xargs -n1
the
day
is
sunny
the
the
the
sunny
is
is

# 扩展测试,忽略
☁  work  cat words.txt | xargs -n2
the day
is sunny
the the
the sunny
is is

# 使用 sort + uniq 函数进行排列
# sort -nr 表示依照数值的大小降序排序
# uniq -c 表示在每列旁边显示该行重复出现的次数
☁  work  cat words.txt | xargs -n1 | sort
day
is
is
is
sunny
sunny
the
the
the
the
☁  work  cat words.txt | xargs -n1 | sort  | uniq -c
   1 day
   3 is
   2 sunny
   4 the

# 使用 awk + print 函数将 1、2 列位置互换
☁  work  cat words.txt | xargs -n1 | sort  | uniq -c | sort -nr | awk '{print $2"  "$1}'
the  4
is  3
sunny  2
day  1

最终脚本:

cat words.txt | xargs -n1 | sort  | uniq -c | awk '{print $1"  "$2}'

方法2

# 唯一不同的就是方法1用了xargs,方法2用了tr
# tr 命令用于转换或删除文件中的字符
# -s:缩减连续重复的字符成指定的单个字符
☁  work  cat words.txt | tr -s ' ' '\n' | sort | uniq -c | sort -r | awk '{ print $2, $1 }'
the 4
is 3
sunny 2
day 1

最终脚本:

cat words.txt | tr -s ' ' '\n' | sort  | uniq -c | awk '{print $1"  "$2}'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值