
ファイル内のすべての単語の数を調べるにはどうすればいいですか?
テキスト パイプまたはドキュメント内の各単語のヒストグラムが必要です。ドキュメントには新しい行と空の行が存在します。を除くすべてを削除しました[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 の初期ソリューションよりも多くのメモリが消費されます。