欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

192. Word Frequency。

程序员文章站 2022-07-15 17:59:01
...

Write a bash script to calculate the frequency of each word in a text file words.txt.

For simplicity sake, you may assume:

  • words.txt contains only lowercase characters and space ’ ’ characters.
  • Each word must consist of lowercase characters only.
  • Words are separated by one or more whitespace characters.

For example, assume that words.txt has the following content:

the day is sunny the the
the sunny is is

Your script should output the following, sorted by descending frequency:

the 4
is 3
sunny 2
day 1

这个题让我感受到了linux命令的强大,至于过程可以大致分为以下几步:

192. Word Frequency。

首先使用tr -s ’ ’ ‘\n’ 将文本中的空格替换成换行符。
使用sort 对其排序。
使用uniq -c 对其进行去重,注意到这里使用完uniq之后会自动计算出单词的频率的。
然后再次使用sort -rn 进行逆向排序。
最后使用awk 将数字和字母进行颠倒放置即可。

cat words.txt | tr -s ' ' '\n' | sort | uniq -c | sort -rn | awk '{print $2,$1}'

还可以使用管道命令grep,但是思路与这个是完全一致的。不过替换了tr的方法使用了grep -oE ‘[a-z]’的方法,不过作用都是一样的。

grep -oE '[a-z]+' words.txt | sort | uniq -c | sort -nr | awk '{print $2" "$1}'