Текст и документы
Частота слов в тексте
Считает самые частые слова, умеет исключать стоп-слова и короткие служебные формы.
Shell
Linux
macOS
Средний
Что делает скрипт
Скрипт приводит текст к нижнему регистру, отделяет слова от знаков препинания и сортирует частоты по убыванию. Можно передать файл со стоп-словами и задать минимальную длину слова. Результат выводится таблицей или сохраняется в файл.
Запуск
Быстрый старт
bash word_frequency.sh --input book.txt --top 30
Скачайте файл, откройте терминал в папке со скриптом и выполните команду.
Другие варианты
bash word_frequency.sh --input article.txt --top 20bash word_frequency.sh --input book.txt --stopwords stop.txt --min-length 4 --output freq.txtcat notes.txt | bash word_frequency.sh --top 10
Что понадобится
Bash 4+
Стандартные grep, sed, tr, sort, uniq, head
Linux
sudo apt install bash
macOS
brew install bash
Исходник
word_frequency.sh
#!/usr/bin/env bash
set -euo pipefail
usage() {
echo "Использование: $0 --input <файл|-> [--top N] [--min-length N] [--stopwords файл] [--output файл]"
}
input="-"
top=25
min_length=3
stopwords=""
output=""
while [[ $# -gt 0 ]]; do
case "$1" in
--input) input="${2:-}"; shift 2 ;;
--top) top="${2:-}"; shift 2 ;;
--min-length) min_length="${2:-}"; shift 2 ;;
--stopwords) stopwords="${2:-}"; shift 2 ;;
--output) output="${2:-}"; shift 2 ;;
-h|--help) usage; exit 0 ;;
*) echo "Неизвестный аргумент: $1" >&2; usage >&2; exit 2 ;;
esac
done
if [[ "$input" != "-" && ! -f "$input" ]]; then
echo "Файл не найден: $input" >&2
exit 2
fi
if [[ -n "$stopwords" && ! -f "$stopwords" ]]; then
echo "Файл стоп-слов не найден: $stopwords" >&2
exit 2
fi
if ! [[ "$top" =~ ^[0-9]+$ ]] || ! [[ "$min_length" =~ ^[0-9]+$ ]]; then
echo "--top и --min-length должны быть числами" >&2
exit 2
fi
tmp_dir="$(mktemp -d)"
trap 'rm -rf -- "$tmp_dir"' EXIT
if [[ "$input" == "-" ]]; then
cat > "$tmp_dir/input.txt"
else
cp -- "$input" "$tmp_dir/input.txt"
fi
upper="АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ"
lower="абвгдеёжзийклмнопрстуфхцчшщъыьэюя"
ascii_upper="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
ascii_lower="abcdefghijklmnopqrstuvwxyz"
sed -e "y/${upper}/${lower}/" -e "y/${ascii_upper}/${ascii_lower}/" "$tmp_dir/input.txt" > "$tmp_dir/lower.txt"
grep -oE '[[:alnum:]_-]+' "$tmp_dir/lower.txt" > "$tmp_dir/words.txt" || true
sed -E 's/^-+//; s/-+$//' "$tmp_dir/words.txt" | grep -vE '^$|^[0-9]+$' > "$tmp_dir/cleaned.txt" || true
if [[ -n "$stopwords" ]]; then
tr -d '\r' < "$stopwords" | sed -e "y/${upper}/${lower}/" -e "y/${ascii_upper}/${ascii_lower}/" | grep -oE '[[:alnum:]_-]+' > "$tmp_dir/stop.txt" || true
grep -vFxf "$tmp_dir/stop.txt" "$tmp_dir/cleaned.txt" > "$tmp_dir/filtered.txt" || true
else
cp "$tmp_dir/cleaned.txt" "$tmp_dir/filtered.txt"
fi
grep -E "^.{$min_length,}$" "$tmp_dir/filtered.txt" > "$tmp_dir/final.txt" || true
sort "$tmp_dir/final.txt" | uniq -c | sort -rn | head -n "$top" > "$tmp_dir/top.txt"
if [[ ! -s "$tmp_dir/top.txt" ]]; then
echo "Слова не найдены" >&2
exit 1
fi
if [[ -n "$output" ]]; then
cp -- "$tmp_dir/top.txt" "$output"
echo "Результат: $output"
else
cat "$tmp_dir/top.txt"
fi
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.