
如何查找文件中每個單字的計數?
我想要文字管道或文件中每個單字的直方圖。文檔中將存在新行和空白行。我把除了 之外的東西都脫光了[a-zA-Z]
。
> cat doc.txt
word second third
word really
> cat doc.txt | ... # then count occurrences of each word \
# and print in descending order separated by delimiter
word 2
really 1
second 1
third 1
它需要具有一定的效率,因為文件是 1GB 文本,並且無法處理指數時間負載。
答案1
嘗試這個:
grep -o '\w*' doc.txt | sort | uniq -c | sort -nr
-o
列印每個匹配項而不是匹配行\w*
匹配單字字符sort
在管道傳輸到 之前對匹配項進行排序uniq
。uniq -c
列印唯一行和出現的次數-c
sort -nr
依出現次數進行反向排序。
輸出:
2 word
1 third
1 second
1 really
選擇:
用於awk
精確輸出:
$ grep -o '\w*' doc.txt \
| awk '{seen[$0]++} END{for(s in seen){print s,seen[s]}}' \
| sort -k2r
word 2
really 1
second 1
third 1
答案2
perl -lnE '
$count{$_}++ for /[[:alpha:]]+/g;
END {
say "@$_" for
sort {$b->[1] <=> $a->[1] || $a->[0] cmp $b->[0]}
map {[$_, $count{$_}]}
keys %count
}
' doc.txt
這將比 pLumo 的初始解決方案消耗更多的記憶體。