Programming Search⌘K

Taskcore

Compute word frequencies

Also called most frequent words of a file, top words of a file, word frequency pipeline, tr sort uniq -c.

Read a file of any size in parts and return its n most frequent words, with a word as a run of ASCII letters in lower case and ties in byte order, as the tr, sort and uniq pipeline does.

Task

Read a text file and return its n most frequent words, with the number of times each word occurs. Rosetta Code gives the task as: "Given a text file and an integer n, print/display the n most common words in the file (and the number of their occurrences) in decreasing frequency."1

The task text leaves some rules open. It says: "A word is a sequence of one or more contiguous letters." It also says: "You are free to define what a letter is" and "You may also choose not to support non US-ASCII characters."1 This page uses these rules:

  • A word is a run of one or more ASCII letters, A to Z and a to z.
  • Each byte that is not an ASCII letter ends a word. So a space, a line break, a digit, an apostrophe, a hyphen and each byte above 0x7F are separators. it's is the two words it and s, and café in UTF-8 gives caf. Rosetta Code allows this: "You may treat a compound word like well-dressed as either one word or two."1
  • Each word changes to lower case before it is counted, because "Uppercase letters are considered equivalent to their lowercase counterparts."1
  • The pairs are sorted by count from high to low. Rosetta Code says: "Words of equal frequency can be listed in any order."1 This page sorts words with the same count in byte order, so each solution gives the same result and a test can compare it.
  • The result holds the first n pairs. If there are fewer than n words, it holds all of them. A file with no words gives an empty list.

The solutions read bytes and do not decode them. So the file can be in UTF-8, in Latin-1 or in another encoding that keeps the ASCII letters as single bytes, and bytes that are not valid UTF-8 do not cause an error. If the file does not exist, the solution reports an error. The file can be larger than the memory: the memory that a solution needs depends on the number of different words, not on the size of the file.

The task Count word frequencies counts the words of a string in memory, and its words keep the letters that are not ASCII and the digits.

Solutions

Each solution reads the file in parts, keeps a map from each word to its count, and sorts the entries of the map at the end. There are two ways to read the parts:

  • Line by line (Python, JavaScript, TypeScript). LF is not a letter, so no word goes across two lines, and each line can be searched on its own. A line is in memory as a whole, so a file of one very long line needs that much memory.
  • Byte by byte through a buffer (Java, C#, Go, Rust, C, C++). The current word stays in a variable across the reads of the buffer, so a word that the end of a buffer cuts is not split. The memory is the map and the longest word.

The steps for each byte:

  1. If the byte is A to Z, add its lower case letter to the current word. If it is a to z, add it.
  2. Else, if the current word is not empty, add 1 to its count in the map and clear it.
  3. At the end of the file, count the current word if it is not empty.
  4. Copy the entries of the map to a list. Sort the list by count from high to low, then by word, and keep the first n entries.

The word is the second key of the sort. The order of a map is often not fixed, and a JavaScript Map "remembers the original insertion order of the keys",2 so without the second key the order of equal counts comes from the map or from the input.

  • Python. open(path, 'rb') gives the file as bytes, and a for loop gives one line at a time. A compiled pattern rb'[a-z]+' finds the words in line.lower(). In re, "Both patterns and strings to be searched can be Unicode strings ( str ) as well as 8-bit strings ( bytes )."3 bytes.lower returns "a copy of the sequence with all the uppercase ASCII characters converted to their corresponding lowercase counterpart."4 A collections.Counter counts the words: "A Counter is a dict subclass for counting hashable objects."5 sorted(counts.items(), key=lambda item: (-item[1], item[0])) sorts them, and [:n] keeps the first n.
  • JavaScript and TypeScript (Node.js). fs.createReadStream(path, { encoding: "latin1" }) changes each byte to one character from U+0000 to U+00FF, so the file needs no decoding and a byte above 0x7F cannot be an ASCII letter. readline.createInterface with crlfDelay: Infinity gives the lines to a for await loop. line.matchAll(/[A-Za-z]+/g) finds the words, and toLowerCase on each match gives only ASCII letters. A Map counts them. The sort compares the counts with y - x, and then the words with < and >, which do not use the locale. The TypeScript file adds types only.
  • Java. A BufferedInputStream of 64 KiB over Files.newInputStream(path) gives one byte for each read(). A StringBuilder holds the current word. counts.merge(word.toString(), 1L, Long::sum) counts it: "If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value".6 Else merge adds 1 with Long::sum. The sort uses Comparator.comparingLong(WordCount::count).reversed().thenComparing(WordCount::word), and the result is a list of the record WordCount.
  • C#. FileStream.Read fills a buffer of 64 KiB, and a StringBuilder holds the current word. CollectionsMarshal.GetValueRefOrAddDefault "Gets a reference to a TValue in the specified dictionary, adding a new entry with a default value if the key does not exist."7 So ++ on that reference counts a word with one lookup. The query is OrderByDescending(e => e.Value).ThenBy(e => e.Key, StringComparer.Ordinal).Take(n).
  • Go. bufio.NewReaderSize(f, 64*1024) and ReadByte give one byte at a time. The current word is a []byte, and counts[string(word)]++ counts it in a map[string]int. slices.SortFunc sorts with cmp.Or(cmp.Compare(b.Count, a.Count), strings.Compare(a.Word, b.Word)). The Go documentation says: "This sort is not guaranteed to be stable."8 No two entries have the same word, so no two entries compare equal, and the order is fixed.
  • Rust. BufReader::with_capacity(64 * 1024, file) with fill_buf and consume gives the buffer, and the code reads its bytes. The map is a HashMap<Vec<u8>, u64>. entry "Gets the given key's corresponding entry in the map for in-place manipulation", but it takes the key by value, so each call needs a new Vec, also for a word that is already in the map.9 get_mut takes a borrowed key: "The key may be any borrowed form of the map's key type".9 So the code calls get_mut(word.as_slice()) first, and it copies the word only for a new key. sort_unstable_by sorts "without preserving the initial order of equal elements",10 which is safe here for the reason given for Go.
  • C. The C library has no map, so the code has a small hash table: FNV-1a hashes of 64 bits, open addressing with linear probing, and a capacity that is a power of 2. The table doubles before it is half full, so a probe always finds an empty slot. getc reads the bytes from the buffer of the stream. qsort sorts the entries, with strcmp as the second key. word_frequencies returns an array that the caller frees with word_frequencies_free, or it returns -1 and sets errno.
  • C++. A std::istreambuf_iterator<char> reads the bytes of a binary std::ifstream. ++counts[word] on a std::unordered_map<std::string, std::size_t> counts a word, because operator[] inserts a count of 0 for a new word. std::ranges::sort sorts the entries, and resize keeps the first n. The result is a std::expected (C++23), and the errors are cannot_open and read_failed.
  • Bash. A pipeline does the work. The Rosetta Code solution for the Unix shell is tr -cs A-Za-z '\n' | tr A-Z a-z | LC_ALL=C sort | uniq -c | sort -rn, and then head with the number of words.11 The history of the task says that Knuth solved it "using literate programming and then critiqued by Doug McIlroy, demonstrating solving the problem in a 6 line Unix shell script".1 For tr, -c means "Complement the set of values specified by string1", and -s means "Replace instances of repeated characters with a single character".12 So tr -cs 'A-Za-z' '\n' changes each run of bytes that are not letters to one LF, and each word is on its own line. uniq -c puts before each line "a count of the number of times the line occurred in the input", but "Repeated lines in the input shall not be detected if they are not adjacent", so sort comes first.13 The solution changes three things (see Pitfalls): each command runs with LC_ALL=C, grep -v '^$' removes an empty line, and sort -k1,1nr -k2,2 sorts the ties by word. Then awk keeps the first n lines and prints word count.

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl, with one file for each in fixtures/.

  • simple: the cat and the hat with n = 2 gives the 2 and and 1. and, cat and hat each occur once, so the byte order selects and.
  • case: The THE the tHe gives the 4.
  • punctuation: it's well-dressed, isn't it? gives it 2, then dressed, isn, s, t and well with 1 each.
  • empty and no-letters: an empty file and a file of digits and punctuation give [].
  • ties: b a c b a c with n = 2 gives a 2 and b 2. All three words have the count 2, so the byte order decides.
  • digits: abc123def 42 x9 gives abc, def and x. A digit ends a word, and a run of digits is not a word.
  • n-zero and n-above-count: n = 0 gives []. An n above the number of words gives all of them.
  • crlf: CR is not a letter, so CRLF line ends do not change the words.
  • non-ascii: café naïve cafe in UTF-8 gives caf, cafe, na and ve. The bytes of é and ï are above 0x7F, so they end words.
  • leading-separators: ...hello, world. Hello gives hello 2 and world 1, and no empty word.
  • no-final-newline: dog cat dog with no LF at the end gives dog 2 and cat 1. The last word is counted at the end of the file.
  • not-utf8: the bytes FF FE between two words ok are not valid UTF-8. They are separators, and the result is ok 2.

The tests also write a file of 100000 lines a b a, and a file of one line of 100000 words, which is longer than a buffer of 64 KiB. The case in cases/errors.jsonl must give the error not-found. The toolchain does not load that file yet, so each test file holds the case by name.

Pitfalls

  • The empty line from tr -cs. If the file starts with a byte that is not a letter, tr -cs changes that run to an LF too, and the first line of its output is empty. uniq -c counts the empty line as a word:
printf '  ...hello, world. Hello\n' |
  LC_ALL=C tr -cs 'A-Za-z' '\n' |
  LC_ALL=C tr 'A-Z' 'a-z' |
  LC_ALL=C sort |
  LC_ALL=C uniq -c |
  awk '{ printf "[%s] %s\n", $2, $1 }'
Output
[] 1
[hello] 2
[world] 1

Remove empty lines with grep -v '^$' before sort. In the other languages, a pattern such as [a-z]+ cannot match an empty string, and the byte loop counts a word only if it is not empty. A split at each separator byte gives empty strings, so skip them.

  • sort -rn does not sort the ties. POSIX says that lines that compare equal on the keys are then compared on all their bytes, "but with -r still in effect, if it was specified".14 So after sort -rn, the words with the same count are in reverse byte order. Add the word as a second key with -k1,1nr -k2,2:
count() {
  printf 'b a c b a c\n' | LC_ALL=C tr -cs 'A-Za-z' '\n' | LC_ALL=C sort | LC_ALL=C uniq -c
}
count | LC_ALL=C sort -rn | awk '{ print $2, $1 }'
echo ---
count | LC_ALL=C sort -k1,1nr -k2,2 | awk '{ print $2, $1 }'
Output
c 2
b 2
a 2
---
a 2
b 2
c 2

Python Counter.most_common has the same problem in a different form: "Elements with equal counts are ordered in the order first encountered".5 So two files with the same words in a different order give two results. Sort with the word as a second key, as all the solutions do.

  • Change the case after the match, or on bytes. On decoded text, str.lower uses the Unicode case mappings: "The lowercasing algorithm used is described in section 3.13.2".4 Some letters that are not ASCII change to ASCII letters. KELVIN SIGN (U+212A) changes to k. LATIN CAPITAL LETTER I WITH DOT ABOVE (U+0130) changes to i and U+0307 COMBINING DOT ABOVE. So a pattern of ASCII letters that runs after lower finds words that are not in the file. bytes.lower changes only A to Z:
import re

# U+212A is KELVIN SIGN, and U+0130 is LATIN CAPITAL LETTER I WITH DOT ABOVE.
text = "\u212aelvin \u0130stanbul"
print(re.findall(r"[a-z]+", text.lower()))
print(re.findall(rb"[a-z]+", text.encode().lower()))
Output
['kelvin', 'i', 'stanbul']
[b'elvin', b'stanbul']

The JavaScript solution matches [A-Za-z]+ first and then changes the case of the match, so only ASCII letters change.

  • Reading the whole file. A solution that reads the whole file into one string needs memory for the whole file. A solution that decodes the file as UTF-8 can stop with an error on bytes that are not valid UTF-8, as in Compute a word count. Read the bytes in parts, and keep only the map.
  • The words of natural language. The rule of this page cuts café into caf and it's into it and s. A rule for real text needs Unicode, and for some languages it needs more: "reliable detection of word boundaries in languages such as Thai, Lao, Chinese, or Japanese requires the use of dictionary lookup or other mechanisms".15 For such text, use a word segmenter that follows UAX #29, and say which rule the program uses.

Code

The build runs the native tests of each language in a pinned toolchain.

word_frequencies.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compute-word-frequencies/.

"""Finds the n most frequent words of a text file."""

import re
from collections import Counter
from os import PathLike

# A word is a run of ASCII letters. The pattern runs on bytes, so the file
# needs no decoding, and each byte that is not a letter ends a word.
WORD = re.compile(rb"[a-z]+")


def word_frequencies(path: str | PathLike[str], n: int) -> list[tuple[str, int]]:
    """Returns the n most frequent words of the file at path, with their counts.

    The words are changed to lower case. The pairs are sorted by count from
    high to low, then by word. Memory grows with the number of different
    words and the length of the longest line, not with the size of the file.
    Raises FileNotFoundError if the file does not exist.
    """
    counts: Counter[bytes] = Counter()
    with open(path, "rb") as f:
        # LF is not a letter, so no word goes across two lines.
        for line in f:
            # bytes.lower changes only A to Z.
            counts.update(WORD.findall(line.lower()))
    # most_common(n) keeps equal counts in the order of first use, so sort
    # with the word as the second key.
    ranked = sorted(counts.items(), key=lambda item: (-item[1], item[0]))
    return [(word.decode("ascii"), count) for word, count in ranked[:n]]
test_word_frequencies.py 41 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compute-word-frequencies/.

import pytest

from word_frequencies import word_frequencies

# name: (the bytes of the file, n, the result)
CASES = {
    "simple": (b"the cat and the hat\n", 2, [("the", 2), ("and", 1)]),
    "case": (b"The THE the tHe\n", 5, [("the", 4)]),
    "punctuation": (b"it's well-dressed, isn't it?\n", 10,
                    [("it", 2), ("dressed", 1), ("isn", 1), ("s", 1), ("t", 1), ("well", 1)]),
    "empty": (b"", 3, []),
    "no-letters": (b"123 ... 42\n-- !!\n", 3, []),
    "ties": (b"b a c b a c\n", 2, [("a", 2), ("b", 2)]),
    "digits": (b"abc123def 42 x9\n", 10, [("abc", 1), ("def", 1), ("x", 1)]),
    "n-zero": (b"the cat and the hat\n", 0, []),
    "n-above-count": (b"x y x\n", 10, [("x", 2), ("y", 1)]),
    "crlf": (b"one two\r\ntwo\r\n", 5, [("two", 2), ("one", 1)]),
    "non-ascii": ("caf\u00e9 na\u00efve cafe\n".encode(), 10, [("caf", 1), ("cafe", 1), ("na", 1), ("ve", 1)]),
    "leading-separators": (b"  ...hello, world. Hello\n", 5, [("hello", 2), ("world", 1)]),
    "no-final-newline": (b"dog cat dog", 5, [("dog", 2), ("cat", 1)]),
    "not-utf8": (b"ok \xff\xfe ok\n", 5, [("ok", 2)]),
    "many-lines": (b"a b a\n" * 100000, 3, [("a", 200000), ("b", 100000)]),
    # One line of 100000 words: longer than one buffer of 64 KiB.
    "long-line": (b"word " * 100000, 3, [("word", 100000)]),
}


@pytest.mark.parametrize("name", CASES)
def test_cases(tmp_path, name):
    data, n, expect = CASES[name]
    path = tmp_path / "input.txt"
    path.write_bytes(data)
    assert word_frequencies(path, n) == expect


def test_not_found(tmp_path):
    with pytest.raises(FileNotFoundError):
        word_frequencies(tmp_path / "missing.txt", 3)
word_frequencies.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-word-frequencies/.

#include "word_frequencies.hpp"

#include <algorithm>
#include <fstream>
#include <iterator>
#include <unordered_map>

std::expected<WordCounts, FrequencyError> word_frequencies(const std::filesystem::path& path, std::size_t n) {
    std::ifstream in(path, std::ios::binary);
    if (!in) {
        return std::unexpected(FrequencyError::cannot_open);
    }
    std::unordered_map<std::string, std::size_t> counts;
    // The current word stays in word across the reads of the stream buffer.
    std::string word;
    for (std::istreambuf_iterator<char> it(in), end; it != end; ++it) {
        const char c = *it;
        if (c >= 'A' && c <= 'Z') {
            word += static_cast<char>(c - 'A' + 'a');
        } else if (c >= 'a' && c <= 'z') {
            word += c;
        } else if (!word.empty()) {
            ++counts[word];  // operator[] inserts a count of 0 for a new word
            word.clear();
        }
    }
    if (in.bad()) {
        return std::unexpected(FrequencyError::read_failed);
    }
    if (!word.empty()) {
        ++counts[word];
    }
    WordCounts ranked(counts.begin(), counts.end());
    // The order of an unordered_map is not fixed, so the word is the second key.
    std::ranges::sort(ranked, [](const auto& a, const auto& b) {
        return a.second != b.second ? a.second > b.second : a.first < b.first;
    });
    ranked.resize(std::min(n, ranked.size()));
    return ranked;
}
word_frequencies.hpp 21 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-word-frequencies/.
// since: C++23 (std::expected)

#pragma once

#include <cstddef>
#include <expected>
#include <filesystem>
#include <string>
#include <utility>
#include <vector>

enum class FrequencyError { cannot_open, read_failed };

using WordCounts = std::vector<std::pair<std::string, std::size_t>>;

// Returns the n most frequent words of the file at path, with their counts. A
// word is a run of ASCII letters, changed to lower case. The pairs are sorted
// by count from high to low, then by word.
std::expected<WordCounts, FrequencyError> word_frequencies(const std::filesystem::path& path, std::size_t n);
test_word_frequencies.cpp 77 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-word-frequencies/.

#include <cstdio>
#include <fstream>
#include <string>
#include <vector>

#include "word_frequencies.hpp"

namespace {

const std::filesystem::path input = "word_frequencies_input.txt";

void write(const std::string& data) {
    std::ofstream out(input, std::ios::binary);
    out.write(data.data(), static_cast<std::streamsize>(data.size()));
}

std::string repeat(const std::string& unit, int times) {
    std::string s;
    for (int i = 0; i < times; i++) {
        s += unit;
    }
    return s;
}

struct test_case {
    const char* name;
    std::string data;
    std::size_t n;
    WordCounts want;
};

}  // namespace

int main() {
    const std::vector<test_case> cases = {
        {"simple", "the cat and the hat\n", 2, {{"the", 2}, {"and", 1}}},
        {"case", "The THE the tHe\n", 5, {{"the", 4}}},
        {"punctuation", "it's well-dressed, isn't it?\n", 10,
         {{"it", 2}, {"dressed", 1}, {"isn", 1}, {"s", 1}, {"t", 1}, {"well", 1}}},
        {"empty", "", 3, {}},
        {"no-letters", "123 ... 42\n-- !!\n", 3, {}},
        {"ties", "b a c b a c\n", 2, {{"a", 2}, {"b", 2}}},
        {"digits", "abc123def 42 x9\n", 10, {{"abc", 1}, {"def", 1}, {"x", 1}}},
        {"n-zero", "the cat and the hat\n", 0, {}},
        {"n-above-count", "x y x\n", 10, {{"x", 2}, {"y", 1}}},
        {"crlf", "one two\r\ntwo\r\n", 5, {{"two", 2}, {"one", 1}}},
        {"non-ascii", "caf\xc3\xa9 na\xc3\xafve cafe\n", 10, {{"caf", 1}, {"cafe", 1}, {"na", 1}, {"ve", 1}}},
        {"leading-separators", "  ...hello, world. Hello\n", 5, {{"hello", 2}, {"world", 1}}},
        {"no-final-newline", "dog cat dog", 5, {{"dog", 2}, {"cat", 1}}},
        {"not-utf8", "ok \xff\xfe ok\n", 5, {{"ok", 2}}},
        {"many-lines", repeat("a b a\n", 100000), 3, {{"a", 200000}, {"b", 100000}}},
        // One line of 100000 words: longer than the stream buffer.
        {"long-line", repeat("word ", 100000), 3, {{"word", 100000}}},
    };
    int failed = 0;
    for (const auto& c : cases) {
        write(c.data);
        auto got = word_frequencies(input, c.n);
        if (!got || *got != c.want) {
            std::fprintf(stderr, "case %s failed\n", c.name);
            failed++;
        }
    }
    auto missing = word_frequencies("no/such/dir/missing.txt", 3);
    if (missing || missing.error() != FrequencyError::cannot_open) {
        std::fprintf(stderr, "case not-found failed\n");
        failed++;
    }
    std::filesystem::remove(input);
    if (failed == 0) {
        std::puts("all cases pass");
    }
    return failed == 0 ? 0 : 1;
}
WordFrequencies.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-word-frequencies/.

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/** Finds the most frequent words of a text file. */
public final class WordFrequencies {
  private WordFrequencies() {}

  /** One word and the number of times it occurs. */
  public record WordCount(String word, long count) {}

  /**
   * Returns the n most frequent words of the file at path. A word is a run of ASCII letters,
   * changed to lower case. The result is sorted by count from high to low, then by word. A
   * missing file throws NoSuchFileException.
   */
  public static List<WordCount> of(Path path, int n) throws IOException {
    Map<String, Long> counts = new HashMap<>();
    // The current word stays in word across the reads of the buffer.
    StringBuilder word = new StringBuilder();
    try (InputStream in = new BufferedInputStream(Files.newInputStream(path), 64 * 1024)) {
      for (int b = 0; b != -1; ) {
        b = in.read();
        if (b >= 'A' && b <= 'Z') {
          word.append((char) (b - 'A' + 'a'));
        } else if (b >= 'a' && b <= 'z') {
          word.append((char) b);
        } else if (word.length() > 0) {
          // A byte that is not a letter, or the end of the file, ends the word.
          counts.merge(word.toString(), 1L, Long::sum);
          word.setLength(0);
        }
      }
    }
    List<WordCount> ranked = new ArrayList<>();
    counts.forEach((w, c) -> ranked.add(new WordCount(w, c)));
    // The order of a HashMap is not fixed, so the word is the second key.
    ranked.sort(
        Comparator.comparingLong(WordCount::count).reversed().thenComparing(WordCount::word));
    return List.copyOf(ranked.subList(0, Math.min(n, ranked.size())));
  }
}
WordFrequenciesTest.java 69 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-word-frequencies/.

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

class WordFrequenciesTest {
  @TempDir Path dir;

  private static WordFrequencies.WordCount wc(String word, long count) {
    return new WordFrequencies.WordCount(word, count);
  }

  private static byte[] utf8(String s) {
    return s.getBytes(StandardCharsets.UTF_8);
  }

  static Stream<Arguments> cases() {
    return Stream.of(
        Arguments.of("simple", utf8("the cat and the hat\n"), 2, List.of(wc("the", 2), wc("and", 1))),
        Arguments.of("case", utf8("The THE the tHe\n"), 5, List.of(wc("the", 4))),
        Arguments.of("punctuation", utf8("it's well-dressed, isn't it?\n"), 10,
            List.of(wc("it", 2), wc("dressed", 1), wc("isn", 1), wc("s", 1), wc("t", 1), wc("well", 1))),
        Arguments.of("empty", utf8(""), 3, List.of()),
        Arguments.of("no-letters", utf8("123 ... 42\n-- !!\n"), 3, List.of()),
        Arguments.of("ties", utf8("b a c b a c\n"), 2, List.of(wc("a", 2), wc("b", 2))),
        Arguments.of("digits", utf8("abc123def 42 x9\n"), 10, List.of(wc("abc", 1), wc("def", 1), wc("x", 1))),
        Arguments.of("n-zero", utf8("the cat and the hat\n"), 0, List.of()),
        Arguments.of("n-above-count", utf8("x y x\n"), 10, List.of(wc("x", 2), wc("y", 1))),
        Arguments.of("crlf", utf8("one two\r\ntwo\r\n"), 5, List.of(wc("two", 2), wc("one", 1))),
        Arguments.of("non-ascii", utf8("caf\u00e9 na\u00efve cafe\n"), 10,
            List.of(wc("caf", 1), wc("cafe", 1), wc("na", 1), wc("ve", 1))),
        Arguments.of("leading-separators", utf8("  ...hello, world. Hello\n"), 5,
            List.of(wc("hello", 2), wc("world", 1))),
        Arguments.of("no-final-newline", utf8("dog cat dog"), 5, List.of(wc("dog", 2), wc("cat", 1))),
        Arguments.of("not-utf8", new byte[] {'o', 'k', ' ', (byte) 0xff, (byte) 0xfe, ' ', 'o', 'k', '\n'}, 5,
            List.of(wc("ok", 2))),
        Arguments.of("many-lines", utf8("a b a\n".repeat(100000)), 3, List.of(wc("a", 200000), wc("b", 100000))),
        // One line of 100000 words: longer than the buffer of 64 KiB.
        Arguments.of("long-line", utf8("word ".repeat(100000)), 3, List.of(wc("word", 100000))));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void wordFrequencies(String name, byte[] data, int n, List<WordFrequencies.WordCount> want)
      throws IOException {
    Path path = dir.resolve(name + ".txt");
    Files.write(path, data);
    assertEquals(want, WordFrequencies.of(path, n));
  }

  @Test
  void notFound() {
    assertThrows(NoSuchFileException.class, () -> WordFrequencies.of(dir.resolve("missing.txt"), 3));
  }
}
word_frequencies.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-word-frequencies/.

#include "word_frequencies.h"

#include <errno.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// A hash table with open addressing and linear probing. A slot with a NULL
// word is empty. The capacity is a power of 2, and the table grows before it
// is half full, so a probe always finds an empty slot.
struct table {
    struct word_freq *slots;
    size_t cap;
    size_t used;
};

// FNV-1a, 64 bits.
static uint64_t hash(const char *s, size_t len) {
    uint64_t h = 14695981039346656037u;
    for (size_t i = 0; i < len; i++) {
        h ^= (unsigned char)s[i];
        h *= 1099511628211u;
    }
    return h;
}

static struct word_freq *find(struct word_freq *slots, size_t cap, const char *word, size_t len) {
    size_t i = hash(word, len) & (cap - 1);
    while (slots[i].word != NULL && strcmp(slots[i].word, word) != 0) {
        i = (i + 1) & (cap - 1);
    }
    return &slots[i];
}

static int grow(struct table *t) {
    size_t cap = t->cap * 2;
    struct word_freq *slots = calloc(cap, sizeof *slots);
    if (slots == NULL) {
        return -1;
    }
    for (size_t i = 0; i < t->cap; i++) {
        if (t->slots[i].word != NULL) {
            *find(slots, cap, t->slots[i].word, strlen(t->slots[i].word)) = t->slots[i];
        }
    }
    free(t->slots);
    t->slots = slots;
    t->cap = cap;
    return 0;
}

// add adds 1 to the count of the word of len bytes, ended by a NUL.
static int add(struct table *t, const char *word, size_t len) {
    if (2 * (t->used + 1) > t->cap && grow(t) != 0) {
        return -1;
    }
    struct word_freq *slot = find(t->slots, t->cap, word, len);
    if (slot->word == NULL) {
        slot->word = malloc(len + 1);
        if (slot->word == NULL) {
            return -1;
        }
        memcpy(slot->word, word, len + 1);
        t->used++;
    }
    slot->count++;
    return 0;
}

static int compare(const void *a, const void *b) {
    const struct word_freq *x = a, *y = b;
    if (x->count != y->count) {
        return x->count > y->count ? -1 : 1;
    }
    // strcmp compares the bytes as unsigned char.
    return strcmp(x->word, y->word);
}

void word_frequencies_free(struct word_freq *words, size_t len) {
    for (size_t i = 0; i < len; i++) {
        free(words[i].word);
    }
    free(words);
}

int word_frequencies(const char *path, size_t n, struct word_freq **out, size_t *len) {
    FILE *f = fopen(path, "rb");
    if (f == NULL) {
        return -1;
    }
    struct table t = {calloc(16, sizeof(struct word_freq)), 16, 0};
    size_t wcap = 64, wlen = 0;
    char *word = malloc(wcap);
    int err = 0;
    if (t.slots == NULL || word == NULL) {
        err = ENOMEM;
    }
    // getc reads from the buffer of the stream. The current word stays in
    // word across the reads of the buffer.
    for (int c = 0; err == 0 && c != EOF;) {
        c = getc(f);
        if (c >= 'A' && c <= 'Z') {
            c += 'a' - 'A';
        }
        if (c >= 'a' && c <= 'z') {
            if (wlen + 1 == wcap) {
                char *bigger = realloc(word, wcap * 2);
                if (bigger == NULL) {
                    err = ENOMEM;
                    break;
                }
                word = bigger;
                wcap *= 2;
            }
            word[wlen++] = (char)c;
        } else if (wlen > 0) {
            // A byte that is not a letter, or the end of the file, ends the word.
            word[wlen] = '\0';
            if (add(&t, word, wlen) != 0) {
                err = ENOMEM;
            }
            wlen = 0;
        }
    }
    if (err == 0 && ferror(f)) {
        err = errno != 0 ? errno : EIO;
    }
    fclose(f);
    free(word);
    // Move the words to the start of the array, sort them, and keep n.
    size_t used = 0;
    for (size_t i = 0; t.slots != NULL && i < t.cap; i++) {
        if (t.slots[i].word != NULL) {
            t.slots[used++] = t.slots[i];
        }
    }
    if (err != 0) {
        word_frequencies_free(t.slots, used);
        errno = err;
        return -1;
    }
    qsort(t.slots, used, sizeof *t.slots, compare);
    size_t keep = used < n ? used : n;
    for (size_t i = keep; i < used; i++) {
        free(t.slots[i].word);
    }
    *out = t.slots;
    *len = keep;
    return 0;
}
word_frequencies.h 24 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-word-frequencies/.

#ifndef WORD_FREQUENCIES_H
#define WORD_FREQUENCIES_H

#include <stddef.h>

struct word_freq {
    char *word;    // a run of ASCII letters in lower case, ended by a NUL
    size_t count;  // the number of times the word occurs
};

// word_frequencies reads the file at path and finds its n most frequent words.
// It stores a new array of at most n entries in *out and its length in *len,
// sorted by count from high to low, then by word, and returns 0. Free the
// array with word_frequencies_free. On an error it returns -1 and sets errno:
// the error of fopen or getc, or ENOMEM.
int word_frequencies(const char *path, size_t n, struct word_freq **out, size_t *len);

// word_frequencies_free frees the array and the words that word_frequencies gave.
void word_frequencies_free(struct word_freq *words, size_t len);

#endif
test_word_frequencies.c 93 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-word-frequencies/.

#include "word_frequencies.h"

#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static const char *path = "word_frequencies_input.txt";

static void write_file(const char *data, size_t n) {
    FILE *f = fopen(path, "wb");
    assert(f != NULL);
    assert(fwrite(data, 1, n, f) == n);
    assert(fclose(f) == 0);
}

// want is a list of words and counts, as "the 2 and 1", or "" for no words.
static void check(const char *name, const char *data, size_t size, size_t n, const char *want) {
    write_file(data, size);
    struct word_freq *words;
    size_t len;
    if (word_frequencies(path, n, &words, &len) != 0) {
        fprintf(stderr, "case %s: error %d\n", name, errno);
        exit(1);
    }
    char got[256] = "";
    for (size_t i = 0; i < len; i++) {
        size_t used = strlen(got);
        snprintf(got + used, sizeof got - used, "%s%s %zu", i > 0 ? " " : "", words[i].word, words[i].count);
    }
    word_frequencies_free(words, len);
    if (strcmp(got, want) != 0) {
        fprintf(stderr, "case %s: got \"%s\", want \"%s\"\n", name, got, want);
        exit(1);
    }
}

// sizeof counts the bytes of the literal, but not the final NUL.
#define CASE(name, data, n, want) check(name, data, sizeof(data) - 1, n, want)

static void check_repeated(const char *name, const char *unit, size_t times, size_t n, const char *want) {
    size_t size = strlen(unit) * times;
    char *data = malloc(size + 1);
    assert(data != NULL);
    for (size_t i = 0; i < times; i++) {
        memcpy(data + i * strlen(unit), unit, strlen(unit));
    }
    check(name, data, size, n, want);
    free(data);
}

int main(void) {
    CASE("simple", "the cat and the hat\n", 2, "the 2 and 1");
    CASE("case", "The THE the tHe\n", 5, "the 4");
    CASE("punctuation", "it's well-dressed, isn't it?\n", 10, "it 2 dressed 1 isn 1 s 1 t 1 well 1");
    CASE("empty", "", 3, "");
    CASE("no-letters", "123 ... 42\n-- !!\n", 3, "");
    CASE("ties", "b a c b a c\n", 2, "a 2 b 2");
    CASE("digits", "abc123def 42 x9\n", 10, "abc 1 def 1 x 1");
    CASE("n-zero", "the cat and the hat\n", 0, "");
    CASE("n-above-count", "x y x\n", 10, "x 2 y 1");
    CASE("crlf", "one two\r\ntwo\r\n", 5, "two 2 one 1");
    CASE("non-ascii", "caf\xc3\xa9 na\xc3\xafve cafe\n", 10, "caf 1 cafe 1 na 1 ve 1");
    CASE("leading-separators", "  ...hello, world. Hello\n", 5, "hello 2 world 1");
    CASE("no-final-newline", "dog cat dog", 5, "dog 2 cat 1");
    CASE("not-utf8", "ok \xff\xfe ok\n", 5, "ok 2");
    check_repeated("many-lines", "a b a\n", 100000, 3, "a 200000 b 100000");
    // One line of 100000 words: longer than the buffer of the stream.
    check_repeated("long-line", "word ", 100000, 3, "word 100000");
    // 1000 different words make the table grow more than once.
    char many[8000] = "";
    for (int i = 0; i < 1000; i++) {
        char w[8] = {(char)('a' + i / 100 % 26), (char)('a' + i / 10 % 10), (char)('a' + i % 10), ' ', 0};
        strcat(many, w);
    }
    strcat(many, "aaa");
    check("many-words", many, strlen(many), 2, "aaa 2 aab 1");

    struct word_freq *words;
    size_t len;
    errno = 0;
    if (word_frequencies("no/such/dir/missing.txt", 3, &words, &len) != -1 || errno != ENOENT) {
        fprintf(stderr, "case not-found: no ENOENT error\n");
        exit(1);
    }
    remove(path);
    puts("all cases pass");
    return 0;
}
WordFrequencies.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-word-frequencies/.

using System.Runtime.InteropServices;
using System.Text;

/// <summary>Finds the most frequent words of a text file.</summary>
public static class WordFrequencies
{
    /// <summary>
    /// Returns the n most frequent words of the file at path. A word is a run of ASCII letters,
    /// changed to lower case. The pairs are sorted by count from high to low, then by word.
    /// </summary>
    /// <exception cref="FileNotFoundException">The file does not exist.</exception>
    public static List<(string Word, long Count)> Read(string path, int n)
    {
        var counts = new Dictionary<string, long>();
        // The current word stays in word across the reads of the buffer.
        var word = new StringBuilder();
        void Add()
        {
            if (word.Length == 0)
            {
                return;
            }
            // One lookup finds the count, or adds a count of 0.
            CollectionsMarshal.GetValueRefOrAddDefault(counts, word.ToString(), out _)++;
            word.Clear();
        }
        using (FileStream stream = File.OpenRead(path))
        {
            var buffer = new byte[64 * 1024];
            int read;
            while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
            {
                foreach (byte b in buffer.AsSpan(0, read))
                {
                    if (b is >= (byte)'A' and <= (byte)'Z')
                    {
                        word.Append((char)(b - 'A' + 'a'));
                    }
                    else if (b is >= (byte)'a' and <= (byte)'z')
                    {
                        word.Append((char)b);
                    }
                    else
                    {
                        Add();
                    }
                }
            }
        }
        Add();
        // The order of a Dictionary is not fixed, so the word is the second key.
        return counts
            .OrderByDescending(e => e.Value)
            .ThenBy(e => e.Key, StringComparer.Ordinal)
            .Take(n)
            .Select(e => (e.Key, e.Value))
            .ToList();
    }
}
WordFrequenciesTests.cs 56 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-word-frequencies/.

using System.Text;
using Xunit;

public sealed class WordFrequenciesTests : IDisposable
{
    private readonly string dir = Directory.CreateTempSubdirectory("word-frequencies-").FullName;

    public void Dispose() => Directory.Delete(dir, recursive: true);

    private string Write(byte[] data)
    {
        string path = Path.Combine(dir, "input.txt");
        File.WriteAllBytes(path, data);
        return path;
    }

    private static byte[] Utf8(string s) => Encoding.UTF8.GetBytes(s);

    // Each expected result is a list of "word count" strings.
    public static TheoryData<string, byte[], int, string[]> Cases => new()
    {
        { "simple", Utf8("the cat and the hat\n"), 2, ["the 2", "and 1"] },
        { "case", Utf8("The THE the tHe\n"), 5, ["the 4"] },
        { "punctuation", Utf8("it's well-dressed, isn't it?\n"), 10, ["it 2", "dressed 1", "isn 1", "s 1", "t 1", "well 1"] },
        { "empty", Utf8(""), 3, [] },
        { "no-letters", Utf8("123 ... 42\n-- !!\n"), 3, [] },
        { "ties", Utf8("b a c b a c\n"), 2, ["a 2", "b 2"] },
        { "digits", Utf8("abc123def 42 x9\n"), 10, ["abc 1", "def 1", "x 1"] },
        { "n-zero", Utf8("the cat and the hat\n"), 0, [] },
        { "n-above-count", Utf8("x y x\n"), 10, ["x 2", "y 1"] },
        { "crlf", Utf8("one two\r\ntwo\r\n"), 5, ["two 2", "one 1"] },
        { "non-ascii", Utf8("caf\u00e9 na\u00efve cafe\n"), 10, ["caf 1", "cafe 1", "na 1", "ve 1"] },
        { "leading-separators", Utf8("  ...hello, world. Hello\n"), 5, ["hello 2", "world 1"] },
        { "no-final-newline", Utf8("dog cat dog"), 5, ["dog 2", "cat 1"] },
        { "not-utf8", [0x6f, 0x6b, 0x20, 0xff, 0xfe, 0x20, 0x6f, 0x6b, 0x0a], 5, ["ok 2"] },
        { "many-lines", Utf8(string.Concat(Enumerable.Repeat("a b a\n", 100000))), 3, ["a 200000", "b 100000"] },
        // One line of 100000 words: longer than the buffer of 64 KiB.
        { "long-line", Utf8(string.Concat(Enumerable.Repeat("word ", 100000))), 3, ["word 100000"] },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Read(string name, byte[] data, int n, string[] want)
    {
        var got = WordFrequencies.Read(Write(data), n).Select(p => $"{p.Word} {p.Count}");
        Assert.Equal(want, got);
        _ = name;
    }

    [Fact]
    public void NotFound() =>
        Assert.Throws<FileNotFoundException>(() => WordFrequencies.Read(Path.Combine(dir, "missing.txt"), 3));
}
wordFrequencies.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-word-frequencies/.

import { createReadStream } from "node:fs";
import { createInterface } from "node:readline";

// Returns the n most frequent words of the file at path, as [word, count]
// pairs. A word is a run of ASCII letters, changed to lower case. The pairs are
// sorted by count from high to low, then by word. A missing file rejects with
// an error whose code is "ENOENT".
export async function wordFrequencies(path, n) {
  const counts = new Map();
  // latin1 maps each byte to one character, so the file needs no decoding, and
  // each byte that is not an ASCII letter ends a word. LF is not a letter, so
  // no word goes across two lines.
  const lines = createInterface({ input: createReadStream(path, { encoding: "latin1" }), crlfDelay: Infinity });
  for await (const line of lines) {
    for (const [match] of line.matchAll(/[A-Za-z]+/g)) {
      const word = match.toLowerCase();
      counts.set(word, (counts.get(word) ?? 0) + 1);
    }
  }
  // < and > compare code units and do not use the locale.
  const ranked = [...counts].sort(([a, x], [b, y]) => y - x || (a < b ? -1 : a > b ? 1 : 0));
  return ranked.slice(0, n);
}
wordFrequencies.test.js 46 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-word-frequencies/.

import assert from "node:assert/strict";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { after, test } from "node:test";

import { wordFrequencies } from "./wordFrequencies.js";

// name: [the bytes of the file, n, the result]
const CASES = {
  simple: ["the cat and the hat\n", 2, [["the", 2], ["and", 1]]],
  case: ["The THE the tHe\n", 5, [["the", 4]]],
  punctuation: ["it's well-dressed, isn't it?\n", 10, [["it", 2], ["dressed", 1], ["isn", 1], ["s", 1], ["t", 1], ["well", 1]]],
  empty: ["", 3, []],
  "no-letters": ["123 ... 42\n-- !!\n", 3, []],
  ties: ["b a c b a c\n", 2, [["a", 2], ["b", 2]]],
  digits: ["abc123def 42 x9\n", 10, [["abc", 1], ["def", 1], ["x", 1]]],
  "n-zero": ["the cat and the hat\n", 0, []],
  "n-above-count": ["x y x\n", 10, [["x", 2], ["y", 1]]],
  crlf: ["one two\r\ntwo\r\n", 5, [["two", 2], ["one", 1]]],
  "non-ascii": [Buffer.from("caf\u00e9 na\u00efve cafe\n", "utf8"), 10, [["caf", 1], ["cafe", 1], ["na", 1], ["ve", 1]]],
  "leading-separators": ["  ...hello, world. Hello\n", 5, [["hello", 2], ["world", 1]]],
  "no-final-newline": ["dog cat dog", 5, [["dog", 2], ["cat", 1]]],
  "not-utf8": [Buffer.from([0x6f, 0x6b, 0x20, 0xff, 0xfe, 0x20, 0x6f, 0x6b, 0x0a]), 5, [["ok", 2]]],
  "many-lines": ["a b a\n".repeat(100000), 3, [["a", 200000], ["b", 100000]]],
  // One line of 100000 words: longer than one buffer of 64 KiB.
  "long-line": ["word ".repeat(100000), 3, [["word", 100000]]],
};

const dir = mkdtempSync(join(tmpdir(), "word-frequencies-"));
after(() => rmSync(dir, { recursive: true, force: true }));

for (const [name, [data, n, expect]] of Object.entries(CASES)) {
  test(name, async () => {
    const path = join(dir, `${name}.txt`);
    writeFileSync(path, data);
    assert.deepEqual(await wordFrequencies(path, n), expect);
  });
}

test("not-found", async () => {
  await assert.rejects(wordFrequencies(join(dir, "missing.txt"), 3), { code: "ENOENT" });
});
wordFrequencies.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-word-frequencies/.

import { createReadStream } from "node:fs";
import { createInterface } from "node:readline";

// Returns the n most frequent words of the file at path, as [word, count]
// pairs. A word is a run of ASCII letters, changed to lower case. The pairs are
// sorted by count from high to low, then by word. A missing file rejects with
// an error whose code is "ENOENT".
export async function wordFrequencies(path: string, n: number): Promise<Array<[string, number]>> {
  const counts = new Map<string, number>();
  // latin1 maps each byte to one character, so the file needs no decoding, and
  // each byte that is not an ASCII letter ends a word. LF is not a letter, so
  // no word goes across two lines.
  const lines = createInterface({ input: createReadStream(path, { encoding: "latin1" }), crlfDelay: Infinity });
  for await (const line of lines) {
    for (const [match] of line.matchAll(/[A-Za-z]+/g)) {
      const word = match.toLowerCase();
      counts.set(word, (counts.get(word) ?? 0) + 1);
    }
  }
  // < and > compare code units and do not use the locale.
  const ranked = [...counts].sort(([a, x], [b, y]) => y - x || (a < b ? -1 : a > b ? 1 : 0));
  return ranked.slice(0, n);
}
wordFrequencies.test.ts 46 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-word-frequencies/.

import assert from "node:assert/strict";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { after, test } from "node:test";

import { wordFrequencies } from "./wordFrequencies.ts";

// name: [the bytes of the file, n, the result]
const CASES: Record<string, [string | Buffer, number, Array<[string, number]>]> = {
  simple: ["the cat and the hat\n", 2, [["the", 2], ["and", 1]]],
  case: ["The THE the tHe\n", 5, [["the", 4]]],
  punctuation: ["it's well-dressed, isn't it?\n", 10, [["it", 2], ["dressed", 1], ["isn", 1], ["s", 1], ["t", 1], ["well", 1]]],
  empty: ["", 3, []],
  "no-letters": ["123 ... 42\n-- !!\n", 3, []],
  ties: ["b a c b a c\n", 2, [["a", 2], ["b", 2]]],
  digits: ["abc123def 42 x9\n", 10, [["abc", 1], ["def", 1], ["x", 1]]],
  "n-zero": ["the cat and the hat\n", 0, []],
  "n-above-count": ["x y x\n", 10, [["x", 2], ["y", 1]]],
  crlf: ["one two\r\ntwo\r\n", 5, [["two", 2], ["one", 1]]],
  "non-ascii": [Buffer.from("caf\u00e9 na\u00efve cafe\n", "utf8"), 10, [["caf", 1], ["cafe", 1], ["na", 1], ["ve", 1]]],
  "leading-separators": ["  ...hello, world. Hello\n", 5, [["hello", 2], ["world", 1]]],
  "no-final-newline": ["dog cat dog", 5, [["dog", 2], ["cat", 1]]],
  "not-utf8": [Buffer.from([0x6f, 0x6b, 0x20, 0xff, 0xfe, 0x20, 0x6f, 0x6b, 0x0a]), 5, [["ok", 2]]],
  "many-lines": ["a b a\n".repeat(100000), 3, [["a", 200000], ["b", 100000]]],
  // One line of 100000 words: longer than one buffer of 64 KiB.
  "long-line": ["word ".repeat(100000), 3, [["word", 100000]]],
};

const dir = mkdtempSync(join(tmpdir(), "word-frequencies-"));
after(() => rmSync(dir, { recursive: true, force: true }));

for (const [name, [data, n, expect]] of Object.entries(CASES)) {
  test(name, async () => {
    const path = join(dir, `${name}.txt`);
    writeFileSync(path, data);
    assert.deepEqual(await wordFrequencies(path, n), expect);
  });
}

test("not-found", async () => {
  await assert.rejects(wordFrequencies(join(dir, "missing.txt"), 3), { code: "ENOENT" });
});
word_frequencies.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-word-frequencies/.

// Package wordfreq finds the most frequent words of a text file.
package wordfreq

import (
	"bufio"
	"cmp"
	"errors"
	"io"
	"os"
	"slices"
	"strings"
)

// WordCount is one word and the number of times it occurs.
type WordCount struct {
	Word  string
	Count int
}

// WordFrequencies returns the n most frequent words of the file at path. A
// word is a run of ASCII letters, changed to lower case. The result is sorted
// by count from high to low, then by word. A missing file gives an error that
// matches fs.ErrNotExist.
func WordFrequencies(path string, n int) ([]WordCount, error) {
	f, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	defer f.Close()
	counts := map[string]int{}
	r := bufio.NewReaderSize(f, 64*1024)
	// The bytes of the current word. They stay across the reads of the buffer,
	// so a word that the end of a buffer cuts is not split.
	var word []byte
	for {
		b, err := r.ReadByte()
		if err != nil && !errors.Is(err, io.EOF) {
			return nil, err
		}
		switch {
		case err == nil && 'a' <= b && b <= 'z':
			word = append(word, b)
		case err == nil && 'A' <= b && b <= 'Z':
			word = append(word, b+'a'-'A')
		case len(word) > 0:
			// A byte that is not a letter, or the end of the file, ends the word.
			counts[string(word)]++
			word = word[:0]
		}
		if err != nil {
			break
		}
	}
	result := make([]WordCount, 0, len(counts))
	for w, c := range counts {
		result = append(result, WordCount{w, c})
	}
	// The order of a map is not fixed, so the word is the second key.
	slices.SortFunc(result, func(a, b WordCount) int {
		return cmp.Or(cmp.Compare(b.Count, a.Count), strings.Compare(a.Word, b.Word))
	})
	return result[:min(n, len(result))], nil
}
word_frequencies_test.go 66 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-word-frequencies/.

package wordfreq

import (
	"errors"
	"io/fs"
	"os"
	"path/filepath"
	"slices"
	"strings"
	"testing"
)

var cases = []struct {
	name string
	data string
	n    int
	want []WordCount
}{
	{"simple", "the cat and the hat\n", 2, []WordCount{{"the", 2}, {"and", 1}}},
	{"case", "The THE the tHe\n", 5, []WordCount{{"the", 4}}},
	{"punctuation", "it's well-dressed, isn't it?\n", 10,
		[]WordCount{{"it", 2}, {"dressed", 1}, {"isn", 1}, {"s", 1}, {"t", 1}, {"well", 1}}},
	{"empty", "", 3, []WordCount{}},
	{"no-letters", "123 ... 42\n-- !!\n", 3, []WordCount{}},
	{"ties", "b a c b a c\n", 2, []WordCount{{"a", 2}, {"b", 2}}},
	{"digits", "abc123def 42 x9\n", 10, []WordCount{{"abc", 1}, {"def", 1}, {"x", 1}}},
	{"n-zero", "the cat and the hat\n", 0, []WordCount{}},
	{"n-above-count", "x y x\n", 10, []WordCount{{"x", 2}, {"y", 1}}},
	{"crlf", "one two\r\ntwo\r\n", 5, []WordCount{{"two", 2}, {"one", 1}}},
	{"non-ascii", "caf\u00e9 na\u00efve cafe\n", 10, []WordCount{{"caf", 1}, {"cafe", 1}, {"na", 1}, {"ve", 1}}},
	{"leading-separators", "  ...hello, world. Hello\n", 5, []WordCount{{"hello", 2}, {"world", 1}}},
	{"no-final-newline", "dog cat dog", 5, []WordCount{{"dog", 2}, {"cat", 1}}},
	{"not-utf8", "ok \xff\xfe ok\n", 5, []WordCount{{"ok", 2}}},
	{"many-lines", strings.Repeat("a b a\n", 100000), 3, []WordCount{{"a", 200000}, {"b", 100000}}},
	// One line of 100000 words: longer than the buffer of 64 KiB.
	{"long-line", strings.Repeat("word ", 100000), 3, []WordCount{{"word", 100000}}},
}

func TestWordFrequencies(t *testing.T) {
	dir := t.TempDir()
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			path := filepath.Join(dir, c.name+".txt")
			if err := os.WriteFile(path, []byte(c.data), 0o644); err != nil {
				t.Fatal(err)
			}
			got, err := WordFrequencies(path, c.n)
			if err != nil {
				t.Fatal(err)
			}
			if !slices.Equal(got, c.want) {
				t.Errorf("got %v, want %v", got, c.want)
			}
		})
	}
}

func TestNotFound(t *testing.T) {
	_, err := WordFrequencies(filepath.Join(t.TempDir(), "missing.txt"), 3)
	if !errors.Is(err, fs.ErrNotExist) {
		t.Errorf("got %v, want fs.ErrNotExist", err)
	}
}
word_frequencies.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-word-frequencies/.

//! Finds the most frequent words of a text file.

use std::collections::HashMap;
use std::fs::File;
use std::io::{self, BufRead, BufReader};
use std::path::Path;

/// Adds 1 to the count of `word` and clears it, if it is not empty.
fn add(counts: &mut HashMap<Vec<u8>, u64>, word: &mut Vec<u8>) {
    if word.is_empty() {
        return;
    }
    match counts.get_mut(word.as_slice()) {
        Some(count) => *count += 1,
        None => {
            counts.insert(word.clone(), 1);
        }
    }
    word.clear();
}

/// Returns the `n` most frequent words of the file at `path`, with their
/// counts. A word is a run of ASCII letters, changed to lower case. The pairs
/// are sorted by count from high to low, then by word. A missing file gives an
/// error of the kind `ErrorKind::NotFound`.
pub fn word_frequencies(path: impl AsRef<Path>, n: usize) -> io::Result<Vec<(String, u64)>> {
    let mut reader = BufReader::with_capacity(64 * 1024, File::open(path)?);
    let mut counts: HashMap<Vec<u8>, u64> = HashMap::new();
    // The bytes of the current word. They stay across the reads of the buffer,
    // so a word that the end of a buffer cuts is not split.
    let mut word = Vec::new();
    loop {
        let buf = reader.fill_buf()?;
        if buf.is_empty() {
            break;
        }
        for &b in buf {
            if b.is_ascii_alphabetic() {
                word.push(b.to_ascii_lowercase());
            } else {
                add(&mut counts, &mut word);
            }
        }
        let len = buf.len();
        reader.consume(len);
    }
    add(&mut counts, &mut word);
    let mut ranked: Vec<(String, u64)> = counts
        .into_iter()
        .map(|(w, c)| (String::from_utf8(w).expect("a word holds only ASCII letters"), c))
        .collect();
    // No two entries have the same word, so an unstable sort gives one order.
    ranked.sort_unstable_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
    ranked.truncate(n);
    Ok(ranked)
}
tests/word_frequencies_test.rs 66 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-word-frequencies/.

use std::fs;
use std::io::ErrorKind;
use std::path::PathBuf;

use algo_compute_word_frequencies::word_frequencies;

/// Writes the bytes to a new file in the temporary directory and returns its path.
fn write(name: &str, data: &[u8]) -> PathBuf {
    let dir = std::env::temp_dir().join(format!("word-frequencies-{}", std::process::id()));
    fs::create_dir_all(&dir).unwrap();
    let path = dir.join(name);
    fs::write(&path, data).unwrap();
    path
}

const CASES: &[(&str, &[u8], usize, &[(&str, u64)])] = &[
    ("simple", b"the cat and the hat\n", 2, &[("the", 2), ("and", 1)]),
    ("case", b"The THE the tHe\n", 5, &[("the", 4)]),
    ("punctuation", b"it's well-dressed, isn't it?\n", 10,
        &[("it", 2), ("dressed", 1), ("isn", 1), ("s", 1), ("t", 1), ("well", 1)]),
    ("empty", b"", 3, &[]),
    ("no-letters", b"123 ... 42\n-- !!\n", 3, &[]),
    ("ties", b"b a c b a c\n", 2, &[("a", 2), ("b", 2)]),
    ("digits", b"abc123def 42 x9\n", 10, &[("abc", 1), ("def", 1), ("x", 1)]),
    ("n-zero", b"the cat and the hat\n", 0, &[]),
    ("n-above-count", b"x y x\n", 10, &[("x", 2), ("y", 1)]),
    ("crlf", b"one two\r\ntwo\r\n", 5, &[("two", 2), ("one", 1)]),
    ("non-ascii", "caf\u{e9} na\u{ef}ve cafe\n".as_bytes(), 10, &[("caf", 1), ("cafe", 1), ("na", 1), ("ve", 1)]),
    ("leading-separators", b"  ...hello, world. Hello\n", 5, &[("hello", 2), ("world", 1)]),
    ("no-final-newline", b"dog cat dog", 5, &[("dog", 2), ("cat", 1)]),
    ("not-utf8", b"ok \xff\xfe ok\n", 5, &[("ok", 2)]),
];

fn pairs(want: &[(&str, u64)]) -> Vec<(String, u64)> {
    want.iter().map(|&(w, c)| (w.to_string(), c)).collect()
}

#[test]
fn cases() {
    for &(name, data, n, want) in CASES {
        let path = write(&format!("{name}.txt"), data);
        assert_eq!(word_frequencies(&path, n).unwrap(), pairs(want), "{name}");
    }
}

#[test]
fn many_lines() {
    let path = write("many-lines.txt", "a b a\n".repeat(100000).as_bytes());
    assert_eq!(word_frequencies(&path, 3).unwrap(), pairs(&[("a", 200000), ("b", 100000)]));
}

#[test]
fn long_line() {
    // One line of 100000 words: longer than the buffer of 64 KiB.
    let path = write("long-line.txt", "word ".repeat(100000).as_bytes());
    assert_eq!(word_frequencies(&path, 3).unwrap(), pairs(&[("word", 100000)]));
}

#[test]
fn not_found() {
    let err = word_frequencies("no/such/dir/missing.txt", 3).unwrap_err();
    assert_eq!(err.kind(), ErrorKind::NotFound);
}
word_frequencies.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compute-word-frequencies/.

# word_frequencies PATH N
# Prints the N most frequent words of the file at PATH, one "word count" line
# each, sorted by count from high to low, then by word. A word is a run of
# ASCII letters, changed to lower case. Returns a nonzero status, and prints
# nothing on stdout, if the file cannot be read.
word_frequencies() {
  [[ -r $1 && ! -d $1 ]] || { printf 'word_frequencies: cannot read %s\n' "$1" >&2; return 1; }
  # LC_ALL=C makes each command work on bytes, so A-Za-z is the 52 ASCII
  # letters, and sort compares bytes. tr -cs changes each run of bytes that
  # are not letters to one LF, so each word is on its own line. If the file starts with a byte
  # that is not a letter, the first line is empty, and grep removes it.
  # sort -k1,1nr -k2,2 sorts by count, then by word, so ties have one order.
  # awk keeps the first N lines and puts the word before the count.
  LC_ALL=C tr -cs 'A-Za-z' '\n' <"$1" |
    LC_ALL=C tr 'A-Z' 'a-z' |
    LC_ALL=C grep -v '^$' |
    LC_ALL=C sort |
    LC_ALL=C uniq -c |
    LC_ALL=C sort -k1,1nr -k2,2 |
    awk -v n="$2" 'NR > n { exit } { print $2, $1 }'
}
test_word_frequencies.bats 43 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compute-word-frequencies/.

bats_require_minimum_version 1.5.0

setup() {
  source "$BATS_TEST_DIRNAME/word_frequencies.sh"
  file="$BATS_TEST_TMPDIR/input.txt"
}

check() { # check BYTES N WANT
  printf '%b' "$1" >"$file"
  run word_frequencies "$file" "$2"
  [ "$status" -eq 0 ]
  [ "$output" = "$(printf '%b' "$3")" ]
}

@test "simple" { check 'the cat and the hat\n' 2 'the 2\nand 1'; }
@test "case" { check 'The THE the tHe\n' 5 'the 4'; }
@test "punctuation" { check "it's well-dressed, isn't it?\n" 10 'it 2\ndressed 1\nisn 1\ns 1\nt 1\nwell 1'; }
@test "empty" { check '' 3 ''; }
@test "no-letters" { check '123 ... 42\n-- !!\n' 3 ''; }
@test "ties" { check 'b a c b a c\n' 2 'a 2\nb 2'; }
@test "digits" { check 'abc123def 42 x9\n' 10 'abc 1\ndef 1\nx 1'; }
@test "n-zero" { check 'the cat and the hat\n' 0 ''; }
@test "n-above-count" { check 'x y x\n' 10 'x 2\ny 1'; }
@test "crlf" { check 'one two\r\ntwo\r\n' 5 'two 2\none 1'; }
@test "non-ascii" { check 'caf\xc3\xa9 na\xc3\xafve cafe\n' 10 'caf 1\ncafe 1\nna 1\nve 1'; }
@test "leading-separators" { check '  ...hello, world. Hello\n' 5 'hello 2\nworld 1'; }
@test "no-final-newline" { check 'dog cat dog' 5 'dog 2\ncat 1'; }
@test "not-utf8" { check 'ok \xff\xfe ok\n' 5 'ok 2'; }

@test "many-lines" {
  yes 'a b a' | head -n 100000 >"$file"
  run word_frequencies "$file" 3
  [ "$output" = "$(printf 'a 200000\nb 100000')" ]
}

@test "not-found" {
  run word_frequencies "$BATS_TEST_TMPDIR/missing.txt" 3
  [ "$status" -ne 0 ]
}

References

  1. Rosetta Code, Word frequency (task text, from acmeism/RosettaCodeData), Task; History
  2. MDN Web Docs, Map, the introduction
  3. The Python Standard Library, re, the introduction (str and bytes patterns)
  4. The Python Standard Library, Built-in Types, bytes.lower; str.lower
  5. The Python Standard Library, collections, Counter objects, Counter; most_common
  6. Java SE 25 API, java.util.Map, merge
  7. .NET API reference, CollectionsMarshal.GetValueRefOrAddDefault
  8. Go standard library, package slices, SortFunc
  9. The Rust Standard Library, std::collections::HashMap, entry; get_mut
  10. The Rust Standard Library, slice, sort_unstable_by
  11. Rosetta Code, Word frequency, UNIX Shell solution (from acmeism/RosettaCodeData), the whole file
  12. The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), tr, OPTIONS (-c, -s)
  13. The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), uniq, DESCRIPTION; OPTIONS (-c)
  14. The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024), sort, DESCRIPTION (the order of lines that compare equal); OPTIONS (-n, -k)
  15. Unicode Standard Annex #29, Unicode Text Segmentation, 2 Conformance

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • the tests did not run in this build
Code (cpp)I0 not checked yet
  • the tests did not run in this build
Code (csharp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (java)I0 not checked yet
  • the tests did not run in this build
Code (javascript)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (rust)I0 not checked yet
  • the tests did not run in this build
Code (typescript)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source