前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Linux 统计文档中各个字母出现的次数,显示各个字母出现的频率

Linux 统计文档中各个字母出现的次数,显示各个字母出现的频率

作者头像
week
发布2018-08-24 14:56:45
1.8K0
发布2018-08-24 14:56:45
举报
文章被收录于专栏:用户画像

一、思路

1、第一个参数来判断脚本执行哪一个功能

-h 显示帮助信息

-c 统计文件 filename 中的 各个字母出现的次数


代码语言:javascript
复制
#echo"param1:$1";  
if [ $1 ="-c"] ;then  
    统计文件 filename 中的 各个字母出现的次数  
elif ["$1" = "-h" ] ;then  
显示帮助信息  
else  
    echo "no such param";  
fi  

2. 第二个参数是文件名称,默认是在当前目录下,我的测试文本是jiangxingqi

3.统计文件 filename 中的 各个字母出现的次数和概率

①将测试文件中的所有字母拆分,存储至t1,字母使用正则表达式来判断^[A-Za-z]+$

②对t1文件中的字母进行去重统计,存储至t2文件

sort t1 |uniq -c|sort -k1nr

③读取t2文件中字母所出现的次数,除以字母的总数即为字母出现的概率

p=`awk 'BEGIN{printf“%.2f%%\n",('$x'/'$cnt')*100}'`

二、shell

代码语言:javascript
复制
#echo "param1:$1";  
p1="-c";  
if [ $1 = $p1 ] ;then  
    file_content=$(cat $2);  
    rm -f t1;  
    touch t1;  
    # the number of alphabet in this file   
    cnt=0;  
    for line in "$file_content"; do  
            # count:the number of char in this line;  
            len=`echo $line|wc -m`  
        #echo $count $line  
            i=1;  
            # the index of alphabet in this line  
            while [ "$i" -lt "$len" ]; do  
              one_word=`echo $line|cut -c$i`  
          if [[ "$one_word" =~ ^[A-Za-z]+$ ]] ;then  
                #echo $i $one_word;  
                ((cnt++))  
                echo "$one_word" >>t1;  
              fi  
        ((i++))  
            done  
    done  
        #echo "the number of alphabet in this file is $cnt";  
    rm -f t2;  
    touch t2;  
    sort t1 |uniq -c|sort -k1nr > t2;  
    t2_content=$(cat "t2");  
    #echo $t2_content;  
    j=0;  
    OLD_IFS="$IFS"  
    IFS=" "  
    arr=($t2_content)  
    IFS="$OLD_IFS"  
    for x in ${arr[@]} ; do  
         b=$(( $j % 2 ))  
             if [ $b = 0 ] ; then  
           letter=${arr[j+1]}           
       p=`awk 'BEGIN{printf “%.2f%%\n",('$x'/'$cnt')*100}'`  
                    echo $letter $x $p;  
                 fi  
         ((j++))  
        done  
elif [ "$1" = "-h" ] ;then  
    echo "help infomation:"  
    echo "1.input command: ./wordcount.sh -c filename   
    function:count the number of character appear in this filename";  
    echo "2.input command: ./wordcount.sh -h   
    function:show the help infomation";  
else  
    echo "no such param";  
fi  

三、运行结果

1. 显示help infomation

2.统计脚本执行结果

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017年12月22日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档