首页 > 解决方案 > 如何使用 bash 从文本文件创建词汇表?

问题描述

我对 bash 完全陌生,正在尝试练习各种简单的任务。如果给定一个文本文件,我如何输出文件中的单词及其频率?例如,如果文本文件包含“我真的很喜欢汉堡”,则输出应如下所示:

汉堡 1

我 1

爱 1

真的 2

我什至不确定如何开始。如何将文本文件加载到 bash 中?你怎么放东西?对不起,非常初学者的问题,但我真的很感激一些帮助,谢谢!

标签: bash

解决方案


你可以通过这种方式做你想做的事:

  1. 获取输入文本文件
  2. 获取输入目录以在其中保存单词文件
  3. 打印带有频率的独特单词。
#!/bin/bash


echo -e "Suggested files: \n"

    ls
    echo -e "\n"

     read -p "Enter the file name :" file

     if [ -e $file ]
     then

        if [ -s $file ]
            then
             echo -e "Enter the directory where do you want to save the file in \n"

             read dir

             words=$(grep -v '^$' $file|tr " " "\n"|sort|uniq)

             grep -v '^$' $file|tr " " "\n" |sort| grep -v '^$' > $dir/file[$j].sorted

             
             for i in $words
             do
                num=$(grep -c "$i" $dir/file[$j].sorted)
                echo -e "The word \e[1;33m$i\e[0m exists \e[1;34m$num\e[0m times in the file \n"
             done 

        else
          echo "The file you have entered is empty"
        fi

    else 
         echo "The file you have entered does not exist"
    fi



推荐阅读