「脚本」词频统计 & 有效电话号码

00192 词频统计

题目描述

写一个 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 实现吗?

力扣地址

  • https://leetcode.com/problems/word-frequency/
  • https://leetcode-cn.com/problems/word-frequency/

解题报告

    1. 先将字符串按照空格切分成行.
[root@localhost ~ ]$ cat words.txt | tr ' ' '\n'
the
day
is
sunny
the
the
the
sunny
is
is
    1. 结果按照字符串顺序排序,将相同的单词聚合到一起
[root@localhost ~ ]$ cat words.txt | tr ' ' '\n' | sort   
day
is
is
is
sunny
sunny
the
the
the
the
    1. 进行相同单词统计个数
[root@localhost ~ ]$ cat words.txt | tr ' ' '\n' | sort | uniq -c
   1 day
   3 is
   2 sunny
   4 the
    1. 词频统计结果按照次数降序排列
[root@localhost ~ ]$ cat words.txt | tr ' ' '\n' | sort | uniq -c | sort -r
   4 the
   3 is
   2 sunny
   1 day
    1. 按照题目要出输出统计结果
[root@localhost ~ ]$ cat words.txt | tr ' ' '\n' | sort | uniq -c | sort -r | awk '{print $2, $1}'
the 4
is 3
sunny 2
day 1

最终答案

本题解由微信公众号小猿刷题提供, 错误之处, 欢迎指正.

cat words.txt | tr ' ' '\n' | sort | uniq -c | sort -r | awk '{print $2, $1}'
小猿刷题

00193 有效电话号码

题目描述

给定一个包含电话号码列表(一行一个电话号码)的文本文件 file.txt,写一个 bash 脚本输出所有有效的电话号码。

你可以假设一个有效的电话号码必须满足以下两种格式: (xxx) xxx-xxxx 或 xxx-xxx-xxxx。(x 表示一个数字)

你也可以假设每行前后没有多余的空格字符。

示例:

假设 file.txt 内容如下:

987-123-4567
123 456 7890
(123) 456-7890

你的脚本应当输出下列有效的电话号码:

987-123-4567
(123) 456-7890

力扣地址

  • https://leetcode.com/problems/valid-phone-numbers/
  • https://leetcode-cn.com/problems/valid-phone-numbers/

解题报告

本题主要是如何去体现电话号码的正则表达式:

  • 第一部分: [0-9]{3}- 或者 ([0-9]{3})
  • 第二部分: [0-9]{3}-
  • 第三部分: [0-9]{4}

转换成正则表达式

^([0-9]{3}-|\([0-9]{3}\) )[0-9]{3}-[0-9]{4}$
基于awk统计

本题解由微信公众号小猿刷题提供, 错误之处, 欢迎指正.

[root@localhost ~ ]$ awk '/^([0-9]{3}-|\([0-9]{3}\) )[0-9]{3}-[0-9]{4}$/' file.txt
987-123-4567
(123) 456-7890

基于grep统计

本题解由微信公众号小猿刷题提供, 错误之处, 欢迎指正.

[root@localhost ~ ]$ grep -e '^\([0-9]\{3\}-\|([0-9]\{3\}) \)[0-9]\{3\}-[0-9]\{4\}$' file.txt 
987-123-4567
(123) 456-7890
小猿刷题

你可能感兴趣的:(「脚本」词频统计 & 有效电话号码)