溫馨提示×

Linux wordcount如何忽略停用詞

小樊
81
2024-09-21 05:05:45

在 Linux 系統(tǒng)中,可以使用 grep、trwc 命令組合來實(shí)現(xiàn)對文本文件中單詞的計(jì)數(shù),同時(shí)忽略停用詞。假設(shè)你有一個(gè)包含停用詞的文本文件 stopwords.txt,內(nèi)容如下:

the
and
is
in
it

現(xiàn)在你想統(tǒng)計(jì)另一個(gè)文本文件 input.txt 中的單詞數(shù)量,同時(shí)忽略 stopwords.txt 中的停用詞。你可以使用以下命令:

grep -oE '\w+' input.txt | tr ' ' '\n' | grep -vE "($(cat stopwords.txt | tr ' ' '|'))" | wc -l

解釋:

  1. grep -oE '\w+' input.txt:從 input.txt 文件中提取所有單詞(連續(xù)的字母、數(shù)字和下劃線)。
  2. tr ' ' '\n':將單詞之間的空格替換為換行符,使每個(gè)單詞單獨(dú)一行。
  3. grep -vE "($(cat stopwords.txt | tr ' ' '|'))":使用擴(kuò)展正則表達(dá)式過濾掉 stopwords.txt 中的停用詞。
  4. wc -l:計(jì)算過濾后的行數(shù),即單詞數(shù)量。

注意:這個(gè)命令假設(shè)停用詞文件中的單詞大小寫敏感。如果你想忽略大小寫,可以將 grep -vE 部分改為 grep -i -vE,或者在讀取停用詞文件時(shí)將所有單詞轉(zhuǎn)換為小寫(或大寫):cat stopwords.txt | tr ' ' '| | tr '[:upper:]' '[:lower:]'。

0