当前位置:网站首页>Shell练习:统计词频
Shell练习:统计词频
2022-07-21 17:00:00 【解忧杂货铺Q】
写一个 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}'
边栏推荐
- Finer grained useeffect
- Spark 读取csv文件操作,option参数解释
- MySQL regexp case insensitive solution
- Write the first myshell program (computer experiment report II)
- js中的三目运算符详解
- 百面机器学习总结
- AirFlow的Scheduling的start_date解释
- Extjs4实例地址和中文文档地址
- Yiwen teaches you five tips for detecting whether MOS tubes are good or bad "suggestions collection"
- MySql中on与where的区别个人总结——分清楚条件应该写在哪里
猜你喜欢
Pytorch学习(一).深度学习回顾和Pytorch简介
Verilog——串行四位加法器和超前四位加法器74HC283
excel 如何删除有颜色的行
Unified payment callback interface of Alipay (applicable to H5, PC and APP)
excel 如何根据身份证号自动匹配性别代码
生产环境TiDB集群缩容TiKV操作步骤
pytorch学习(一):线性回归
Anaconda安装jupyter lab + jupyterlsp(代码提示,代码纠错)详细搭建过程
How to cache with blob object in browser
CDH 6.1 environment construction graphic tutorial
随机推荐
WebSockets 和 Server-Sent Events
STM32 HAL库 SPI总是读出FF的问题解决!
编码之前先保证你的硬件稳定连接!!!
支招!不能参加PMP考试怎么办?
How does idea import automatically
8位补码booth一位乘法器
数据分析与挖掘2
Intégration de l'efk avec l'odoo pour réaliser la visualisation des journaux
Why not overwrite when pasting in excel
Fast Fourier transform, Lagrange interpolation, three thousand words with examples, sister chapters, application of FFT and string matching
状态管理之 Zustand
更细粒度的 useEffect
用odoo集成EFK,實現日志可視化
CDH 6.1 环境搭建图文教程
Integrate efk with odoo to realize log visualization
R语言的&和&&注意事项
Physical address introduction "recommended collection"
How to add text before and after text in batch in Excel
Why do you always say that you should prepare for the first construction after the second construction examination? You must not know these points!
线程池7个参数的含义