SHELL9. 统计每个单词出现的个数
描述
写一个 bash脚本以统计一个文本文件 nowcoder.txt 中每个单词出现的个数。Bash 解法, 执行用时: 2ms, 内存消耗: 352KB, 提交时间: 2020-12-28
declare -A map while read line do arr=($line) for i in ${arr[@]} do if [ -z ${map[$i]} ];then map[$i]=1 else ((map[$i]++)) fi done done < nowcoder.txt mm=() for value in ${map[@]} do mm[${#mm[@]}]=${value} done for ((i=0;i<${#mm[*]};i++)) do for ((j=$i+1;j<${#mm[*]};j++)) do if [ ${mm[$i]} -gt ${mm[$j]} ];then qq=${mm[$i]} mm[$i]=${mm[$j]} mm[$j]=$qq fi done done for ((k=0;k<${#mm[*]};k++)) do for key in ${!map[@]} do if [ ${map[$key]} -eq ${mm[$k]} ];then echo $key ${map[$key]} fi done done
Bash 解法, 执行用时: 2ms, 内存消耗: 392KB, 提交时间: 2020-12-30
declare -A map while read line do arr=($line) for i in ${arr[@]} do if [ -z ${map[$i]} ];then map[$i]=1 else ((map[$i]++)) fi done done < nowcoder.txt mm=() for value in ${map[@]} do mm[${#mm[@]}]=${value} done for ((i=0;i<${#mm[*]};i++)) do for ((j=$i+1;j<${#mm[*]};j++)) do if [ ${mm[$i]} -gt ${mm[$j]} ];then qq=${mm[$i]} mm[$i]=${mm[$j]} mm[$j]=$qq fi done done for ((k=0;k<${#mm[*]};k++)) do for key in ${!map[@]} do if [ ${map[$key]} -eq ${mm[$k]} ];then echo $key ${map[$key]} fi done done
Bash 解法, 执行用时: 3ms, 内存消耗: 356KB, 提交时间: 2021-04-11
declare -A map while read line do arr=$line for i in ${arr[@]} do if [ -z ${map[$i]} ] then map[$i]=1 else ((map[$i]++)) fi done done < nowcoder.txt mm=() for value in ${map[@]} do mm[${#mm[@]}]=${value} done len=${#mm[@]} for ((i=0;i<len;i++)) do for ((j=i+1;j<len;j++)) do if [ ${mm[$i]} -gt ${mm[$j]} ] then tmp=${mm[$i]} mm[$i]=${mm[$j]} mm[$j]=$tmp fi done done for ((k=0;k<${#mm[*]};k++)) do for key in ${!map[@]} do if [ ${map[$key]} -eq ${mm[$k]} ] then echo $key ${map[$key]} fi done done
Bash 解法, 执行用时: 3ms, 内存消耗: 356KB, 提交时间: 2021-02-08
#!/bin/bash #cat $1 | tr -s ' ' '\n' |sort |uniq -c|sort |awk '{print $2" "$1}' declare -A map while read linestr do arr=($linestr) for key in ${arr[@]} do if [ -z "${map[$key]}" ];then map[$key]=1 else ((map[$key]++)) fi done done<nowcoder.txt mm=() for vlaue in ${map[@]} do mm[${#mm[@]}]=${vlaue} done for ((a=0;a<${#mm[*]};a++));do for ((k=$a+1;k<${#mm[*]};k++));do if [ ${mm[$a]} -gt ${mm[$k]} ];then qq=${mm[$a]} mm[$a]=${mm[$k]} mm[$k]=$qq fi done done for ((k=0;k<${#mm[*]};k++));do for key in ${!map[@]};do if [ ${map[$key]} -eq ${mm[$k]} ];then echo $key ${map[$key]} fi done done
Bash 解法, 执行用时: 3ms, 内存消耗: 360KB, 提交时间: 2021-07-04
#!/bin/bash declare -A map while read line #记录每个单词出现的次数 do for ch in $line;do map[$ch]=$((map[$ch]+1)) done done < nowcoder.txt declare -a arr # ${!map[@]}获取map的所有索引 for key in ${!map[@]};do arr[${map[$key]}]=$key done for index in ${!arr[@]};do echo "${arr[$index]} $index" done