如何在 Unix/Linux 中找到文件中出现频率最高的 10 个单词?
我尝试在 Unix 中使用这个命令:
sort file.txt | uniq -c | sort -nr | head -10
但是我不确定它是否正确以及它是否向我显示了大文件中 10 个最常用的单词。
最佳答案
我有一个 shell 演示来处理你的问题,即使你有一个文件在一行中包含多个单词
wordcount.sh
#!/bin/bash
# filename: wordcount.sh
# usage: word count
# handle position arguments
if [ $# -ne 1 ]
then
echo "Usage: $0 filename"
exit -1
fi
# realize word count
printf "%-14s%s\n" "Word" "Count"
cat $1 | tr 'A-Z' 'a-z' | \
egrep -o "\b[[:alpha:]]+\b" | \
awk '{ count[$0]++ }
END{
for(ind in count)
{ printf("%-14s%d\n",ind,count[ind]); }
}' | sort -k2 -n -r | head -n 10
只需运行 ./wordcount.sh filename.txt
解释
使用tr命令将所有大写字母转换为小写字母,然后使用egrep命令抓取文本中的所有单词并逐项输出。最后用awk命令和关联数组实现字数统计功能,根据出现次数递减输出。 .
关于linux - 如何在 Unix/Linux 中找到文件中出现频率最高的 10 个词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53377867/