Leetcode192. 统计词频

192. 统计词频

写一个 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

题意概述:通过bash脚本实现txt文本的词频排序。

解决报告:

思路大致分为以下几个步骤:

  • 打开文本
  • 空格替换为换行符
  • 排序
  • 去重统计
  • 第二关键字排序
  • 输出
# Read from the file words.txt and output the word frequency list to stdout.
cat words.txt | xargs -n 1 | sort | uniq -c | sort -nr | awk '{print $2" "$1}'
posted @ 2021-08-11 09:28  dinghao1262  阅读(62)  评论(0)    收藏  举报