Linux终端的乐趣之把玩字词计数


Linux 命令行有很多的乐趣,我们可以很容易并且完善地执行很多繁琐的任务。比如,我们计算一个文本文件中字和字符的出现频率,这就是我们打算在这篇文章中讲到的。

立刻来到我们脑海的命令,计算字和字符在一个文本文件中出现频率的 Linux 命令是 wc 命令。

在使用的脚本来分析文本文件之前,我们必须有一个文本文件。为了保持一致性,我们将创建一个文本文件,man命令的输出如下所述。

  1. $ man man > man.txt

以上命令是将man命令的使用方式导入到man.txt文件里。

我们希望能得到最平常的单词,对之前我们新建的文件执行如下脚本。

  1. $ cat man.txt | tr ' ''\012'| tr '[:upper:]''[:lower:]'| tr -d '[:punct:]'| grep -v '[^a-z]'| sort | uniq -c | sort -rn | head

Sample Output

  1. 7557
  2. 262 the
  3. 163 to
  4. 112is
  5. 112 a
  6. 78 of
  7. 78 manual
  8. 76and
  9. 64if
  10. 63 be

上面的脚本,输出了最常使用的十个单词。

如何看单个的字母呢?那就用如下的命令。

  1. $ echo 'tecmint team'| fold -w1

Sample Output

  1. t
  2. e
  3. c
  4. m
  5. i
  6. n
  7. t
  8. t
  9. e
  10. a
  11. m

注: -w1只是设定了长度

现在我们将从那个文本文件中掰下来的每一个字母,对结果进行排序,得到所需的输出频率的十个最常见的字符。

  1. $ fold -w1 < man.txt | sort | uniq -c | sort -rn | head

Sample Output

  1. 8579
  2. 2413 e
  3. 1987 a
  4. 1875 t
  5. 1644 i
  6. 1553 n
  7. 1522 o
  8. 1514 s
  9. 1224 r
  10. 1021 l

如何区分大小写呢?之前我们都是忽略大小写的。所以,用如下命令。

  1. $ fold -w1 < man.txt | sort | tr '[:lower:]''[:upper:]'| uniq -c | sort -rn | head -20

Sample Output

  1. 11636
  2. 2504 E
  3. 2079 A
  4. 2005 T
  5. 1729 I
  6. 1645 N
  7. 1632 S
  8. 1580 o
  9. 1269 R
  10. 1055 L
  11. 836 H
  12. 791 P
  13. 766 D
  14. 753 C
  15. 725 M
  16. 690 U
  17. 605 F
  18. 504 G
  19. 352 Y
  20. 344.

请检查上面的输出,标点符号居然包括在内。让我们干掉他,用tr 命令。GO:

  1. $ fold -w1 < man.txt | tr '[:lower:]''[:upper:]'| sort | tr -d '[:punct:]'| uniq -c | sort -rn | head -20

Sample Output

  1. 11636
  2. 2504 E
  3. 2079 A
  4. 2005 T
  5. 1729 I
  6. 1645 N
  7. 1632 S
  8. 1580 O
  9. 1550
  10. 1269 R
  11. 1055 L
  12. 836 H
  13. 791 P
  14. 766 D
  15. 753 C
  16. 725 M
  17. 690 U
  18. 605 F
  19. 504 G
  20. 352 Y

现在,我们有了三个文本,那就让我们用如下命令查看结果吧。

  1. $ cat *.txt | fold -w1 | tr '[:lower:]''[:upper:]'| sort | tr -d '[:punct:]'| uniq -c | sort -rn | head -8

Sample Output

  1. 11636
  2. 2504 E
  3. 2079 A
  4. 2005 T
  5. 1729 I
  6. 1645 N
  7. 1632 S
  8. 1580 O

下一步我们将会生成那些罕见的至少十个字母长的单词。以下是简单的脚本:

  1. $ cat man.txt | tr '''\012'| tr '[:upper:]''[:lower:]'| tr -d '[:punct:]'| tr -d '[0-9]'| sort | uniq -c | sort -n | grep -E '..................'| head

Sample Output

  1. 1──────────────────────────────────────────
  2. 1 a all
  3. 1 abc any or all arguments within are optional
  4. 1 able see setlocale for precise details
  5. 1 ab options delimited by cannot be used together
  6. 1 achieved byusing the less environment variable
  7. 1 a child process returned a nonzero exit status
  8. 1 act asifthis option was supplied using the name as a filename
  9. 1 activate local mode format and display local manual files
  10. 1 acute accent

注: 上面的.越来越多,其实,我们可以使用.{10} 得到同样的效果。

这些简单的脚本,让我们知道最频繁出现的单词和英语中的字符。

现在结束了。下次我会在这里讲到另一个有趣的话题,你应该会喜欢读。还有别忘了向我们提供您的宝贵意见。

本文永久更新链接地址:

相关内容