Taskcore
Count word frequencies
Also called word count, word frequency, most common words, top n words, count occurrences in a map.
Split a text into words, change each word to lower case, count the words in a map, and return the n most frequent words, with ties in code point order.
- Evidence
- Code in 10 languages
Task
Count how many times each word occurs in a text. Return the n most frequent words with their counts.
A word is a run of characters that are ASCII letters, ASCII digits or not ASCII. Every other ASCII character ends a word. So a space, a newline, a full stop, an apostrophe, a hyphen and an underscore are all separators. Change each word to lower case before you count it, so Stop and stop are the same word.
Sort the words by count from high to low. If two words have the same count, sort them in code point order. Then return the first n pairs. If there are fewer than n words, return all of them. A text with no words gives an empty list.
The text contains no character at or above U+D800, so the byte order of UTF-8, the code unit order of UTF-16 and the code point order are the same. The only upper case letters are A to Z. These limits keep the result the same in every language.
Solutions
Each solution has three steps. It finds the words, it counts them in a map, and it sorts the map entries with two keys. The second key is the word. It makes the order fixed, because the order of a hash map is not fixed.
- Python.
re.findallwith[A-Za-z0-9\u0080-\U0010FFFF]+finds the words, andcollections.Countercounts them.sorted(counts.items(), key=lambda item: (-item[1], item[0]))[:n]gives the result. The key-item[1]puts high counts first. Strings compare by code point. - JavaScript and TypeScript. The regular expression
/[A-Za-z0-9\u{80}-\u{10FFFF}]+/gufinds the words, and aMapcounts them. The sort compares the counts withy - x. If they are equal,||goes on to<and>on the words. These operators compare UTF-16 code units, and they do not use the locale. - Java.
Patternfinds the words.Map.merge(word, 1L, Long::sum)counts them. The sort usesComparator.comparingLong(WordCount::count).reversed().thenComparing(WordCount::word). The code callstoLowerCase(Locale.ROOT), nottoLowerCase(). - C#. A
[GeneratedRegex]finds the words, and aDictionarycounts them. The query isOrderByDescending(e => e.Value).ThenBy(e => e.Key, StringComparer.Ordinal).Take(n). - Go.
strings.FieldsFuncsplits the text at each run of separators. Amap[string]intcounts the words.slices.SortFuncsorts withcmp.Or(cmp.Compare(b.Count, a.Count), strings.Compare(a.Word, b.Word)). Go compares strings byte by byte. - Rust.
text.split(is_separator)gives the words and some empty strings, which the code skips.*counts.entry(word.to_lowercase()).or_insert(0) += 1counts them.sort_unstable_byis safe here, because no two entries have the same word, so no two entries are equal. - C++. A loop finds the words, and
++counts[word]on astd::unordered_mapcounts them.operator[]inserts a zero count for a new word.std::ranges::sortsorts the entries.std::stringcompares eachcharasunsigned char, so UTF-8 words sort by code point. - C. The C library has no map. The code copies the text, puts a null character in place of each separator, and changes
AtoZto lower case. It sorts the words withqsortandstrcmp, so equal words are next to each other, and counts each run. A secondqsortorders the counts.strcmpcompares bytes asunsigned char. - Bash. A pipeline does all the work.
tr -c 'A-Za-z0-9\200-\377' '\n'puts each word on its own line.tr 'A-Z' 'a-z'changes the case.sort | uniq -ccounts the lines, andsort -k1,1nr -k2,2orders them.head -nkeeps the firstn. Each command runs withLC_ALL=C, so it works on bytes.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
emptyandno-words: an empty text and a text of only separators give[].case:Word,word,WORDandwOrDare one word with the count 4.ties:pear,figandappleeach occur twice. The result isapple,fig,pear, not the order of the input.fold-before-sort:Zebra applegivesapplebeforezebra. If you sort before you change the case,Zebracomes first.n-zeroandn-above-count:n = 0gives[]. Annabove the number of words gives all of them.non-ascii:café,naïveand日本語are words. A rule that keeps only ASCII letters splits them.code-point-order:f é egivese,f,é. The code point ofé(U+00E9) is above the code point off.apostrophe:don'tis the two wordsdonandt. This is the rule of the task. Natural language needs a different rule (see the pitfalls).digits:66and66aare words, and they are different words.separators: a tab, a carriage return, an underscore and a hyphen each end a word.
Pitfalls
- The tie order of
most_common.Counter.most_commonputs elements with equal counts in the order it first saw them. So the result depends on the input order:
This code runs but gives a wrong answer on purpose.
from collections import Counter
counts = Counter("pear fig apple fig pear apple".split())
print(counts.most_common(2))
[('pear', 2), ('fig', 2)]
from collections import Counter
counts = Counter("pear fig apple fig pear apple".split())
print(sorted(counts.items(), key=lambda item: (-item[1], item[0]))[:2])
[('apple', 2), ('fig', 2)]
- The order of a hash map. The Go specification does not specify the iteration order over a map, and the order can change from one loop to the next. Rust
HashMapand C++std::unordered_mapalso have no fixed order. A result that comes from the order of a map can change on each run. This program loops over the same map 100 times and reports if it saw more than one order:
package main
import "fmt"
func main() {
counts := map[string]int{"apple": 2, "fig": 2, "pear": 2, "plum": 2, "kiwi": 2, "lime": 2}
orders := map[string]bool{}
for range 100 {
order := ""
for word := range counts {
order += word + " "
}
orders[order] = true
}
fmt.Println("more than one order:", len(orders) > 1)
}
more than one order: true
\wis ASCII. In JavaScript,\wis[A-Za-z0-9_], also with theuflag. In Java,\wis[a-zA-Z_0-9]unless you setUNICODE_CHARACTER_CLASS. So a split on\W+breakscaféintocaf.\walso counts_as part of a word:
This code runs but gives a wrong answer on purpose.
console.log("café naïve under_score".match(/\w+/gu));
[ 'caf', 'na', 've', 'under_score' ]
- A split on one space.
split(" ")gives an empty string for two spaces in a row, and it keeps the punctuation in the words. Sostop.andstopare different words:
This code runs but gives a wrong answer on purpose.
console.log("Stop. Stop, stop!".toLowerCase().split(" "));
[ 'stop.', '', 'stop,', 'stop!' ]
- Lower case that depends on the locale. In Java,
toLowerCase()uses the default locale. In a Turkish locale,Ibecomesı(U+0131), soTITLEdoes not becometitle. UsetoLowerCase(Locale.ROOT). In C#,ToLowerInvariantdoes the same job:
This code runs but gives a wrong answer on purpose.
import java.util.Locale;
public class Main {
public static void main(String[] args) {
Locale.setDefault(Locale.forLanguageTag("tr-TR"));
System.out.println("TITLE".toLowerCase());
System.out.println("TITLE".toLowerCase(Locale.ROOT));
}
}
tıtle
title
- A comparison that depends on the locale.
localeComparesorts by the rules of a language, so it putsébetweeneandf. That order is good for people, but it is not code point order, and it can change from one locale to the next. In C#,ThenBywith no comparer uses the default comparer, and for strings that comparer uses the current culture. GiveStringComparer.Ordinal:
This code runs but gives a wrong answer on purpose.
console.log(["f", "é", "e"].sort((a, b) => a.localeCompare(b)));
console.log(["f", "é", "e"].sort());
[ 'e', 'é', 'f' ]
[ 'e', 'f', 'é' ]
- Lower case is not case folding. The task changes only
AtoZ. For text in other languages, full case folding is a different operation. Pythoncasefoldchangesßtoss, soStraßeandSTRASSEbecome one word.lowerkeeps them apart:
print("Straße".lower(), "STRASSE".lower())
print("Straße".casefold(), "STRASSE".casefold())
straße strasse
strasse strasse
-
tolowerandisalnumin C. These functions take anint. If the value is not anunsigned charvalue and is notEOF, the behavior is undefined. A UTF-8 byte in acharcan be negative, so cast it tounsigned charfirst. The result of these functions also depends on the current locale. The C solution compares the bytes withAtoZitself. -
uniqwithoutsort.uniqjoins only lines that are next to each other. So you must sort the words beforeuniq -c. SetLC_ALL=Con eachsort. In other locales,sortuses the collation rules of the locale, and the order of the words can change. -
A word for people is a different rule. The rule of this task splits
don'tande-mail. For natural language, use the word boundaries of Unicode Standard Annex #29. In JavaScript,Intl.Segmenterwithgranularity: "word"follows these rules, andisWordLikemarks the segments that are words:
const segmenter = new Intl.Segmenter("en", { granularity: "word" });
const segments = segmenter.segment("Don't stop, e-mail 3.14");
console.log([...segments].filter((s) => s.isWordLike).map((s) => s.segment));
[ "Don't", 'stop', 'e', 'mail', '3.14' ]
Related tasks
- Split a string: split a text at separators.
- Sort a list of records: sort by two keys, one of them in reverse.
- Remove duplicates from a list: another job that uses a map or a set to find equal values.
- Read a file line by line and Read from standard input: read the text to count.
- UTF-8: why byte order is code point order.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/count-word-frequencies/.
import re
from collections import Counter
# A word is a run of ASCII letters, ASCII digits and characters that are not ASCII.
WORD = re.compile(r"[A-Za-z0-9\u0080-\U0010FFFF]+")
def top_words(text: str, n: int) -> list[tuple[str, int]]:
"""Return the n most frequent words of text with their counts.
The order is by count from high to low, then by word in code point order.
"""
counts = Counter(word.lower() for word in WORD.findall(text))
# most_common orders equal counts by first occurrence, so sort with the
# word as the second key.
return sorted(counts.items(), key=lambda item: (-item[1], item[0]))[:n]
test_top_words.py 36 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/count-word-frequencies/.
import pytest
from top_words import top_words
# name: (text, n, the expected (word, count) pairs)
CASES = {
"sentence": ("the cat and the hat and the bat", 3, [("the", 3), ("and", 2), ("bat", 1)]),
"all-words": ("one two two three three three", 10, [("three", 3), ("two", 2), ("one", 1)]),
"punctuation": ("Stop. Stop, stop! Go?", 2, [("stop", 3), ("go", 1)]),
"lines": ("red green\nblue red\ngreen red\n", 2, [("red", 3), ("green", 2)]),
"empty": ("", 3, []),
"no-words": (" ... ,!? \n", 3, []),
"case": ("Word word WORD wOrD", 1, [("word", 4)]),
"ties": ("pear fig apple fig pear apple", 3, [("apple", 2), ("fig", 2), ("pear", 2)]),
"fold-before-sort": ("Zebra apple", 2, [("apple", 1), ("zebra", 1)]),
"n-zero": ("a b c", 0, []),
"n-above-count": ("a b a", 10, [("a", 2), ("b", 1)]),
"non-ascii": ("café naïve café 日本語 naïve café", 3, [("café", 3), ("naïve", 2), ("日本語", 1)]),
"code-point-order": ("f é e", 3, [("e", 1), ("f", 1), ("é", 1)]),
"apostrophe": ("don't stop, don't", 3, [("don", 2), ("t", 2), ("stop", 1)]),
"digits": ("route 66 and route 66a 66", 3, [("66", 2), ("route", 2), ("66a", 1)]),
"separators": (
"tab\there\r\nunder_score-dash",
10,
[("dash", 1), ("here", 1), ("score", 1), ("tab", 1), ("under", 1)],
),
}
@pytest.mark.parametrize("name", CASES)
def test_top_words(name: str) -> None:
text, n, want = CASES[name]
assert top_words(text, n) == want
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-word-frequencies/.
#include "top_words.hpp"
#include <algorithm>
#include <unordered_map>
namespace {
// A byte is part of a word if it is an ASCII letter or digit, or if it is not
// ASCII. Each byte of a multibyte UTF-8 sequence is 0x80 or more. The code does
// not call std::isalnum, because its result depends on the locale.
bool is_word_byte(unsigned char c) {
return c >= 0x80 || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9');
}
} // namespace
std::vector<std::pair<std::string, std::int64_t>> top_words(std::string_view text, std::size_t n) {
std::unordered_map<std::string, std::int64_t> counts;
std::string word;
for (std::size_t i = 0; i <= text.size(); ++i) {
unsigned char c = i < text.size() ? static_cast<unsigned char>(text[i]) : ' ';
if (is_word_byte(c)) {
word += (c >= 'A' && c <= 'Z') ? static_cast<char>(c - 'A' + 'a') : static_cast<char>(c);
} else if (!word.empty()) {
++counts[word]; // operator[] adds a missing key with the value 0
word.clear();
}
}
// The order of an unordered_map is not specified, so sort by both keys.
// std::string compares chars as unsigned char, which for UTF-8 is code
// point order.
std::vector<std::pair<std::string, std::int64_t>> out(counts.begin(), counts.end());
std::ranges::sort(out, [](const auto& a, const auto& b) {
return a.second != b.second ? a.second > b.second : a.first < b.first;
});
out.resize(std::min(n, out.size()));
return out;
}
top_words.hpp 16 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-word-frequencies/.
#pragma once
#include <cstddef>
#include <cstdint>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
// Returns the n most frequent words of the UTF-8 text with their counts, by
// count from high to low, then by word in byte order, which for UTF-8 is code
// point order.
std::vector<std::pair<std::string, std::int64_t>> top_words(std::string_view text, std::size_t n);
test_top_words.cpp 45 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-word-frequencies/.
#include <cstdio>
#include <string>
#include <utility>
#include <vector>
#include "top_words.hpp"
int main() {
using Counts = std::vector<std::pair<std::string, std::int64_t>>;
struct Case {
const char* name;
const char* text;
std::size_t n;
Counts want;
};
const std::vector<Case> cases = {
{"sentence", "the cat and the hat and the bat", 3, {{"the", 3}, {"and", 2}, {"bat", 1}}},
{"all-words", "one two two three three three", 10, {{"three", 3}, {"two", 2}, {"one", 1}}},
{"punctuation", "Stop. Stop, stop! Go?", 2, {{"stop", 3}, {"go", 1}}},
{"lines", "red green\nblue red\ngreen red\n", 2, {{"red", 3}, {"green", 2}}},
{"empty", "", 3, {}},
{"no-words", " ... ,!? \n", 3, {}},
{"case", "Word word WORD wOrD", 1, {{"word", 4}}},
{"ties", "pear fig apple fig pear apple", 3, {{"apple", 2}, {"fig", 2}, {"pear", 2}}},
{"fold-before-sort", "Zebra apple", 2, {{"apple", 1}, {"zebra", 1}}},
{"n-zero", "a b c", 0, {}},
{"n-above-count", "a b a", 10, {{"a", 2}, {"b", 1}}},
{"non-ascii", "café naïve café 日本語 naïve café", 3, {{"café", 3}, {"naïve", 2}, {"日本語", 1}}},
{"code-point-order", "f é e", 3, {{"e", 1}, {"f", 1}, {"é", 1}}},
{"apostrophe", "don't stop, don't", 3, {{"don", 2}, {"t", 2}, {"stop", 1}}},
{"digits", "route 66 and route 66a 66", 3, {{"66", 2}, {"route", 2}, {"66a", 1}}},
{"separators", "tab\there\r\nunder_score-dash", 10, {{"dash", 1}, {"here", 1}, {"score", 1}, {"tab", 1}, {"under", 1}}},
};
int failures = 0;
for (const auto& c : cases) {
if (top_words(c.text, c.n) != c.want) {
std::fprintf(stderr, "case %s failed\n", c.name);
++failures;
}
}
return failures == 0 ? 0 : 1;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-word-frequencies/.
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/** Counts the words of a text and returns the most frequent ones. */
public final class TopWords {
/** A word and the number of times it occurs. */
public record WordCount(String word, long count) {}
// A word is a run of ASCII letters, ASCII digits and characters that are not ASCII.
private static final Pattern WORD = Pattern.compile("[A-Za-z0-9\\x{80}-\\x{10FFFF}]+");
private TopWords() {}
/**
* Returns the n most frequent words of text, by count from high to low, then by word in code
* point order.
*/
public static List<WordCount> topWords(String text, int n) {
Map<String, Long> counts = new HashMap<>();
Matcher m = WORD.matcher(text);
while (m.find()) {
// Locale.ROOT: the default locale can change the mapping, for example in Turkish.
counts.merge(m.group().toLowerCase(Locale.ROOT), 1L, Long::sum);
}
// String.compareTo compares UTF-16 code units. Below U+D800 that is code point order.
return counts.entrySet().stream()
.map(e -> new WordCount(e.getKey(), e.getValue()))
.sorted(
Comparator.comparingLong(WordCount::count).reversed().thenComparing(WordCount::word))
.limit(n)
.toList();
}
}
TopWordsTest.java 42 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-word-frequencies/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class TopWordsTest {
record WordCount(String word, long count) {}
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("sentence", "the cat and the hat and the bat", 3, List.of(new WordCount("the", 3), new WordCount("and", 2), new WordCount("bat", 1))),
Arguments.of("all-words", "one two two three three three", 10, List.of(new WordCount("three", 3), new WordCount("two", 2), new WordCount("one", 1))),
Arguments.of("punctuation", "Stop. Stop, stop! Go?", 2, List.of(new WordCount("stop", 3), new WordCount("go", 1))),
Arguments.of("lines", "red green\nblue red\ngreen red\n", 2, List.of(new WordCount("red", 3), new WordCount("green", 2))),
Arguments.of("empty", "", 3, List.of()),
Arguments.of("no-words", " ... ,!? \n", 3, List.of()),
Arguments.of("case", "Word word WORD wOrD", 1, List.of(new WordCount("word", 4))),
Arguments.of("ties", "pear fig apple fig pear apple", 3, List.of(new WordCount("apple", 2), new WordCount("fig", 2), new WordCount("pear", 2))),
Arguments.of("fold-before-sort", "Zebra apple", 2, List.of(new WordCount("apple", 1), new WordCount("zebra", 1))),
Arguments.of("n-zero", "a b c", 0, List.of()),
Arguments.of("n-above-count", "a b a", 10, List.of(new WordCount("a", 2), new WordCount("b", 1))),
Arguments.of("non-ascii", "café naïve café 日本語 naïve café", 3, List.of(new WordCount("café", 3), new WordCount("naïve", 2), new WordCount("日本語", 1))),
Arguments.of("code-point-order", "f é e", 3, List.of(new WordCount("e", 1), new WordCount("f", 1), new WordCount("é", 1))),
Arguments.of("apostrophe", "don't stop, don't", 3, List.of(new WordCount("don", 2), new WordCount("t", 2), new WordCount("stop", 1))),
Arguments.of("digits", "route 66 and route 66a 66", 3, List.of(new WordCount("66", 2), new WordCount("route", 2), new WordCount("66a", 1))),
Arguments.of("separators", "tab\there\r\nunder_score-dash", 10, List.of(new WordCount("dash", 1), new WordCount("here", 1), new WordCount("score", 1), new WordCount("tab", 1), new WordCount("under", 1))));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void topWords(String name, String text, int n, List<WordCount> want) {
List<WordCount> got =
TopWords.topWords(text, n).stream().map(w -> new WordCount(w.word(), w.count())).toList();
assertEquals(want, got);
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-word-frequencies/.
#include "top_words.h"
#include <stdlib.h>
#include <string.h>
// A byte is part of a word if it is an ASCII letter or digit, or if it is not
// ASCII. Each byte of a multibyte UTF-8 sequence is 0x80 or more. The code
// does not call isalnum, because its result depends on the locale.
static int is_word_byte(unsigned char c) {
return c >= 0x80 || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9');
}
// strcmp compares the bytes as unsigned char, so this is code point order.
static int by_word(const void *a, const void *b) {
return strcmp(*(char *const *)a, *(char *const *)b);
}
static int by_count_then_word(const void *a, const void *b) {
const struct word_count *x = a, *y = b;
if (x->count != y->count) {
return x->count < y->count ? 1 : -1;
}
return strcmp(x->word, y->word);
}
int top_words(const char *text, size_t n, struct word_counts *out) {
*out = (struct word_counts){0};
size_t len = strlen(text);
// The copy has a null character in place of each separator byte, so each
// word in it is a C string.
char *buf = malloc(len + 1);
// There are at most len / 2 + 1 words.
char **words = malloc((len / 2 + 1) * sizeof *words);
if (buf == NULL || words == NULL) {
free(buf);
free(words);
return -1;
}
size_t nwords = 0;
for (size_t i = 0; i < len; i++) {
unsigned char c = (unsigned char)text[i];
if (!is_word_byte(c)) {
buf[i] = '\0';
continue;
}
buf[i] = (c >= 'A' && c <= 'Z') ? (char)(c - 'A' + 'a') : (char)c;
if (i == 0 || buf[i - 1] == '\0') {
words[nwords++] = &buf[i];
}
}
buf[len] = '\0';
// The C library has no map. Sort the words, so equal words are next to
// each other, and count each run.
qsort(words, nwords, sizeof *words, by_word);
struct word_count *items = malloc((nwords + 1) * sizeof *items);
if (items == NULL) {
free(buf);
free(words);
return -1;
}
size_t nitems = 0;
for (size_t i = 0; i < nwords; i++) {
if (nitems > 0 && strcmp(items[nitems - 1].word, words[i]) == 0) {
items[nitems - 1].count++;
} else {
items[nitems++] = (struct word_count){words[i], 1};
}
}
free(words);
// qsort is not stable, but no two items are equal under this order.
qsort(items, nitems, sizeof *items, by_count_then_word);
*out = (struct word_counts){items, nitems < n ? nitems : n, buf};
return 0;
}
void word_counts_free(struct word_counts *wc) {
free(wc->items);
free(wc->buf);
*wc = (struct word_counts){0};
}
top_words.h 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-word-frequencies/.
#ifndef TOP_WORDS_H
#define TOP_WORDS_H
#include <stddef.h>
// A word and the number of times it occurs. word points into the buffer of
// the struct word_counts that holds it.
struct word_count {
const char *word;
size_t count;
};
// The result of top_words. Free it with word_counts_free.
struct word_counts {
struct word_count *items;
size_t len;
char *buf; // the lower case words, each ended by a null character
};
// top_words counts the words of the UTF-8 string text and stores the n most
// frequent ones in *out, by count from high to low, then by word in byte
// order, which for UTF-8 is code point order. It returns 0, or -1 if there is
// no memory.
int top_words(const char *text, size_t n, struct word_counts *out);
void word_counts_free(struct word_counts *wc);
#endif
test_top_words.c 43 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-word-frequencies/.
#include "top_words.h"
#include <stdio.h>
#include <string.h>
static int failures = 0;
static void check(const char *name, const char *text, size_t n, const struct word_count *want,
size_t want_len) {
struct word_counts got;
int ok = top_words(text, n, &got) == 0 && got.len == want_len;
for (size_t i = 0; ok && i < want_len; i++) {
ok = strcmp(got.items[i].word, want[i].word) == 0 && got.items[i].count == want[i].count;
}
if (!ok) {
fprintf(stderr, "case %s failed\n", name);
failures++;
}
word_counts_free(&got);
}
int main(void) {
check("sentence", "the cat and the hat and the bat", 3, ((const struct word_count[]){{"the", 3}, {"and", 2}, {"bat", 1}}), 3);
check("all-words", "one two two three three three", 10, ((const struct word_count[]){{"three", 3}, {"two", 2}, {"one", 1}}), 3);
check("punctuation", "Stop. Stop, stop! Go?", 2, ((const struct word_count[]){{"stop", 3}, {"go", 1}}), 2);
check("lines", "red green\nblue red\ngreen red\n", 2, ((const struct word_count[]){{"red", 3}, {"green", 2}}), 2);
check("empty", "", 3, NULL, 0);
check("no-words", " ... ,!? \n", 3, NULL, 0);
check("case", "Word word WORD wOrD", 1, ((const struct word_count[]){{"word", 4}}), 1);
check("ties", "pear fig apple fig pear apple", 3, ((const struct word_count[]){{"apple", 2}, {"fig", 2}, {"pear", 2}}), 3);
check("fold-before-sort", "Zebra apple", 2, ((const struct word_count[]){{"apple", 1}, {"zebra", 1}}), 2);
check("n-zero", "a b c", 0, NULL, 0);
check("n-above-count", "a b a", 10, ((const struct word_count[]){{"a", 2}, {"b", 1}}), 2);
check("non-ascii", "café naïve café 日本語 naïve café", 3, ((const struct word_count[]){{"café", 3}, {"naïve", 2}, {"日本語", 1}}), 3);
check("code-point-order", "f é e", 3, ((const struct word_count[]){{"e", 1}, {"f", 1}, {"é", 1}}), 3);
check("apostrophe", "don't stop, don't", 3, ((const struct word_count[]){{"don", 2}, {"t", 2}, {"stop", 1}}), 3);
check("digits", "route 66 and route 66a 66", 3, ((const struct word_count[]){{"66", 2}, {"route", 2}, {"66a", 1}}), 3);
check("separators", "tab\there\r\nunder_score-dash", 10, ((const struct word_count[]){{"dash", 1}, {"here", 1}, {"score", 1}, {"tab", 1}, {"under", 1}}), 5);
return failures == 0 ? 0 : 1;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-word-frequencies/.
using System.Text.RegularExpressions;
/// <summary>Counts the words of a text and returns the most frequent ones.</summary>
public static partial class WordCounter
{
// A word is a run of ASCII letters, ASCII digits and UTF-16 units that are not ASCII.
[GeneratedRegex(@"[A-Za-z0-9\u0080-\uFFFF]+")]
private static partial Regex Word();
/// <summary>
/// Returns the n most frequent words of text, by count from high to low, then by word in
/// code point order.
/// </summary>
public static List<(string Word, long Count)> TopWords(string text, int n)
{
var counts = new Dictionary<string, long>();
foreach (Match m in Word().Matches(text))
{
var word = m.Value.ToLowerInvariant();
counts[word] = counts.GetValueOrDefault(word) + 1;
}
// StringComparer.Ordinal compares UTF-16 code units. The default comparer of
// ThenBy depends on the culture.
return counts
.OrderByDescending(e => e.Value)
.ThenBy(e => e.Key, StringComparer.Ordinal)
.Take(n)
.Select(e => (e.Key, e.Value))
.ToList();
}
}
TopWordsTests.cs 35 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-word-frequencies/.
using Xunit;
public sealed class TopWordsTests
{
public static TheoryData<string, string, int, (string, long)[]> Cases => new()
{
{ "sentence", "the cat and the hat and the bat", 3, [("the", 3), ("and", 2), ("bat", 1)] },
{ "all-words", "one two two three three three", 10, [("three", 3), ("two", 2), ("one", 1)] },
{ "punctuation", "Stop. Stop, stop! Go?", 2, [("stop", 3), ("go", 1)] },
{ "lines", "red green\nblue red\ngreen red\n", 2, [("red", 3), ("green", 2)] },
{ "empty", "", 3, [] },
{ "no-words", " ... ,!? \n", 3, [] },
{ "case", "Word word WORD wOrD", 1, [("word", 4)] },
{ "ties", "pear fig apple fig pear apple", 3, [("apple", 2), ("fig", 2), ("pear", 2)] },
{ "fold-before-sort", "Zebra apple", 2, [("apple", 1), ("zebra", 1)] },
{ "n-zero", "a b c", 0, [] },
{ "n-above-count", "a b a", 10, [("a", 2), ("b", 1)] },
{ "non-ascii", "café naïve café 日本語 naïve café", 3, [("café", 3), ("naïve", 2), ("日本語", 1)] },
{ "code-point-order", "f é e", 3, [("e", 1), ("f", 1), ("é", 1)] },
{ "apostrophe", "don't stop, don't", 3, [("don", 2), ("t", 2), ("stop", 1)] },
{ "digits", "route 66 and route 66a 66", 3, [("66", 2), ("route", 2), ("66a", 1)] },
{ "separators", "tab\there\r\nunder_score-dash", 10, [("dash", 1), ("here", 1), ("score", 1), ("tab", 1), ("under", 1)] },
};
[Theory]
[MemberData(nameof(Cases))]
public void TopWords(string name, string text, int n, (string, long)[] want)
{
Assert.NotNull(name);
Assert.Equal(want, WordCounter.TopWords(text, n));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-word-frequencies/.
// A word is a run of ASCII letters, ASCII digits and characters that are not ASCII.
const WORD = /[A-Za-z0-9\u{80}-\u{10FFFF}]+/gu;
/**
* Returns the n most frequent words of text as [word, count] pairs, by count
* from high to low, then by word in code point order.
*/
export function topWords(text, n) {
const counts = new Map();
for (const [word] of text.matchAll(WORD)) {
const key = word.toLowerCase();
counts.set(key, (counts.get(key) ?? 0) + 1);
}
// < compares UTF-16 code units. Below U+D800 that is code point order.
return [...counts]
.sort(([a, x], [b, y]) => y - x || (a < b ? -1 : a > b ? 1 : 0))
.slice(0, n);
}
topWords.test.js 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-word-frequencies/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { topWords } from "./topWords.js";
const cases = [
["sentence", "the cat and the hat and the bat", 3, [["the", 3], ["and", 2], ["bat", 1]]],
["all-words", "one two two three three three", 10, [["three", 3], ["two", 2], ["one", 1]]],
["punctuation", "Stop. Stop, stop! Go?", 2, [["stop", 3], ["go", 1]]],
["lines", "red green\nblue red\ngreen red\n", 2, [["red", 3], ["green", 2]]],
["empty", "", 3, []],
["no-words", " ... ,!? \n", 3, []],
["case", "Word word WORD wOrD", 1, [["word", 4]]],
["ties", "pear fig apple fig pear apple", 3, [["apple", 2], ["fig", 2], ["pear", 2]]],
["fold-before-sort", "Zebra apple", 2, [["apple", 1], ["zebra", 1]]],
["n-zero", "a b c", 0, []],
["n-above-count", "a b a", 10, [["a", 2], ["b", 1]]],
["non-ascii", "café naïve café 日本語 naïve café", 3, [["café", 3], ["naïve", 2], ["日本語", 1]]],
["code-point-order", "f é e", 3, [["e", 1], ["f", 1], ["é", 1]]],
["apostrophe", "don't stop, don't", 3, [["don", 2], ["t", 2], ["stop", 1]]],
["digits", "route 66 and route 66a 66", 3, [["66", 2], ["route", 2], ["66a", 1]]],
["separators", "tab\there\r\nunder_score-dash", 10, [["dash", 1], ["here", 1], ["score", 1], ["tab", 1], ["under", 1]]],
];
for (const [name, text, n, want] of cases) {
test(name, () => assert.deepEqual(topWords(text, n), want));
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-word-frequencies/.
// A word is a run of ASCII letters, ASCII digits and characters that are not ASCII.
const WORD = /[A-Za-z0-9\u{80}-\u{10FFFF}]+/gu;
/**
* Returns the n most frequent words of text as [word, count] pairs, by count
* from high to low, then by word in code point order.
*/
export function topWords(text: string, n: number): [string, number][] {
const counts = new Map<string, number>();
for (const [word] of text.matchAll(WORD)) {
const key = word.toLowerCase();
counts.set(key, (counts.get(key) ?? 0) + 1);
}
// < compares UTF-16 code units. Below U+D800 that is code point order.
return [...counts]
.sort(([a, x], [b, y]) => y - x || (a < b ? -1 : a > b ? 1 : 0))
.slice(0, n);
}
topWords.test.ts 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-word-frequencies/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { topWords } from "./topWords.ts";
const cases: [string, string, number, [string, number][]][] = [
["sentence", "the cat and the hat and the bat", 3, [["the", 3], ["and", 2], ["bat", 1]]],
["all-words", "one two two three three three", 10, [["three", 3], ["two", 2], ["one", 1]]],
["punctuation", "Stop. Stop, stop! Go?", 2, [["stop", 3], ["go", 1]]],
["lines", "red green\nblue red\ngreen red\n", 2, [["red", 3], ["green", 2]]],
["empty", "", 3, []],
["no-words", " ... ,!? \n", 3, []],
["case", "Word word WORD wOrD", 1, [["word", 4]]],
["ties", "pear fig apple fig pear apple", 3, [["apple", 2], ["fig", 2], ["pear", 2]]],
["fold-before-sort", "Zebra apple", 2, [["apple", 1], ["zebra", 1]]],
["n-zero", "a b c", 0, []],
["n-above-count", "a b a", 10, [["a", 2], ["b", 1]]],
["non-ascii", "café naïve café 日本語 naïve café", 3, [["café", 3], ["naïve", 2], ["日本語", 1]]],
["code-point-order", "f é e", 3, [["e", 1], ["f", 1], ["é", 1]]],
["apostrophe", "don't stop, don't", 3, [["don", 2], ["t", 2], ["stop", 1]]],
["digits", "route 66 and route 66a 66", 3, [["66", 2], ["route", 2], ["66a", 1]]],
["separators", "tab\there\r\nunder_score-dash", 10, [["dash", 1], ["here", 1], ["score", 1], ["tab", 1], ["under", 1]]],
];
for (const [name, text, n, want] of cases) {
test(name, () => assert.deepEqual(topWords(text, n), want));
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-word-frequencies/.
// Package wordfreq counts the words of a text.
package wordfreq
import (
"cmp"
"slices"
"strings"
"unicode/utf8"
)
// WordCount is a word and the number of times it occurs.
type WordCount struct {
Word string
Count int
}
// isSeparator tells if r ends a word: an ASCII character that is not a letter
// or a digit.
func isSeparator(r rune) bool {
if r >= utf8.RuneSelf {
return false
}
return !('a' <= r && r <= 'z' || 'A' <= r && r <= 'Z' || '0' <= r && r <= '9')
}
// TopWords returns the n most frequent words of text, by count from high to
// low, then by word in code point order.
func TopWords(text string, n int) []WordCount {
counts := make(map[string]int)
for _, word := range strings.FieldsFunc(text, isSeparator) {
counts[strings.ToLower(word)]++
}
// The iteration order of a map is not specified, so sort by both keys.
out := make([]WordCount, 0, len(counts))
for word, count := range counts {
out = append(out, WordCount{word, count})
}
// Strings compare by bytes. For UTF-8 that is code point order.
slices.SortFunc(out, func(a, b WordCount) int {
return cmp.Or(cmp.Compare(b.Count, a.Count), strings.Compare(a.Word, b.Word))
})
return out[:min(n, len(out))]
}
top_words_test.go 42 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-word-frequencies/.
package wordfreq
import (
"slices"
"testing"
)
func TestTopWords(t *testing.T) {
cases := []struct {
name string
text string
n int
want []WordCount
}{
{"sentence", "the cat and the hat and the bat", 3, []WordCount{{"the", 3}, {"and", 2}, {"bat", 1}}},
{"all-words", "one two two three three three", 10, []WordCount{{"three", 3}, {"two", 2}, {"one", 1}}},
{"punctuation", "Stop. Stop, stop! Go?", 2, []WordCount{{"stop", 3}, {"go", 1}}},
{"lines", "red green\nblue red\ngreen red\n", 2, []WordCount{{"red", 3}, {"green", 2}}},
{"empty", "", 3, []WordCount{}},
{"no-words", " ... ,!? \n", 3, []WordCount{}},
{"case", "Word word WORD wOrD", 1, []WordCount{{"word", 4}}},
{"ties", "pear fig apple fig pear apple", 3, []WordCount{{"apple", 2}, {"fig", 2}, {"pear", 2}}},
{"fold-before-sort", "Zebra apple", 2, []WordCount{{"apple", 1}, {"zebra", 1}}},
{"n-zero", "a b c", 0, []WordCount{}},
{"n-above-count", "a b a", 10, []WordCount{{"a", 2}, {"b", 1}}},
{"non-ascii", "café naïve café 日本語 naïve café", 3, []WordCount{{"café", 3}, {"naïve", 2}, {"日本語", 1}}},
{"code-point-order", "f é e", 3, []WordCount{{"e", 1}, {"f", 1}, {"é", 1}}},
{"apostrophe", "don't stop, don't", 3, []WordCount{{"don", 2}, {"t", 2}, {"stop", 1}}},
{"digits", "route 66 and route 66a 66", 3, []WordCount{{"66", 2}, {"route", 2}, {"66a", 1}}},
{"separators", "tab\there\r\nunder_score-dash", 10, []WordCount{{"dash", 1}, {"here", 1}, {"score", 1}, {"tab", 1}, {"under", 1}}},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
if got := TopWords(c.text, c.n); !slices.Equal(got, c.want) {
t.Errorf("TopWords(%q, %d) = %v, want %v", c.text, c.n, got, c.want)
}
})
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-word-frequencies/.
//! Counts the words of a text and returns the most frequent ones.
use std::collections::HashMap;
/// Tells if `c` ends a word: an ASCII character that is not a letter or a digit.
fn is_separator(c: char) -> bool {
c.is_ascii() && !c.is_ascii_alphanumeric()
}
/// Returns the `n` most frequent words of `text` with their counts, by count
/// from high to low, then by word in code point order.
pub fn top_words(text: &str, n: usize) -> Vec<(String, u64)> {
let mut counts: HashMap<String, u64> = HashMap::new();
for word in text.split(is_separator).filter(|w| !w.is_empty()) {
*counts.entry(word.to_lowercase()).or_insert(0) += 1;
}
let mut out: Vec<(String, u64)> = counts.into_iter().collect();
// The order of a HashMap is not specified, so sort by both keys. A String
// compares by bytes, which for UTF-8 is code point order.
out.sort_unstable_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
out.truncate(n);
out
}
tests/top_words_test.rs 33 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-word-frequencies/.
use algo_count_word_frequencies::top_words;
type Case = (&'static str, &'static str, usize, &'static [(&'static str, u64)]);
const CASES: &[Case] = &[
("sentence", "the cat and the hat and the bat", 3, &[("the", 3), ("and", 2), ("bat", 1)]),
("all-words", "one two two three three three", 10, &[("three", 3), ("two", 2), ("one", 1)]),
("punctuation", "Stop. Stop, stop! Go?", 2, &[("stop", 3), ("go", 1)]),
("lines", "red green\nblue red\ngreen red\n", 2, &[("red", 3), ("green", 2)]),
("empty", "", 3, &[]),
("no-words", " ... ,!? \n", 3, &[]),
("case", "Word word WORD wOrD", 1, &[("word", 4)]),
("ties", "pear fig apple fig pear apple", 3, &[("apple", 2), ("fig", 2), ("pear", 2)]),
("fold-before-sort", "Zebra apple", 2, &[("apple", 1), ("zebra", 1)]),
("n-zero", "a b c", 0, &[]),
("n-above-count", "a b a", 10, &[("a", 2), ("b", 1)]),
("non-ascii", "café naïve café 日本語 naïve café", 3, &[("café", 3), ("naïve", 2), ("日本語", 1)]),
("code-point-order", "f é e", 3, &[("e", 1), ("f", 1), ("é", 1)]),
("apostrophe", "don't stop, don't", 3, &[("don", 2), ("t", 2), ("stop", 1)]),
("digits", "route 66 and route 66a 66", 3, &[("66", 2), ("route", 2), ("66a", 1)]),
("separators", "tab\there\r\nunder_score-dash", 10, &[("dash", 1), ("here", 1), ("score", 1), ("tab", 1), ("under", 1)]),
];
#[test]
fn cases() {
for &(name, text, n, want) in CASES {
let want: Vec<(String, u64)> = want.iter().map(|&(w, c)| (w.to_string(), c)).collect();
assert_eq!(top_words(text, n), want, "{name}");
}
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/count-word-frequencies/.
# top_words TEXT N prints the N most frequent words of TEXT, one "word count"
# line each, by count from high to low, then by word in byte order.
top_words() {
local count word
# LC_ALL=C makes tr, sort and uniq work on bytes. Each byte of a multibyte
# UTF-8 sequence is in \200-\377, so it stays in its word, and the byte order
# of UTF-8 is code point order.
printf '%s\n' "$1" |
LC_ALL=C tr -c 'A-Za-z0-9\200-\377' '\n' |
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 |
head -n "$2" |
while read -r count word; do
printf '%s %s\n' "$word" "$count"
done
}
test_top_words.bats 32 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/count-word-frequencies/.
setup() {
source "$BATS_TEST_DIRNAME/top_words.sh"
}
# check TEXT N WANT compares the output with WANT, which has one "word count"
# line for each word.
check() {
top_words "$1" "$2" >"$BATS_TEST_TMPDIR/got"
printf '%s' "$3" >"$BATS_TEST_TMPDIR/want"
cmp "$BATS_TEST_TMPDIR/got" "$BATS_TEST_TMPDIR/want"
}
@test "sentence" { check $'the cat and the hat and the bat' 3 $'the 3\nand 2\nbat 1\n'; }
@test "all-words" { check $'one two two three three three' 10 $'three 3\ntwo 2\none 1\n'; }
@test "punctuation" { check $'Stop. Stop, stop! Go?' 2 $'stop 3\ngo 1\n'; }
@test "lines" { check $'red green\nblue red\ngreen red\n' 2 $'red 3\ngreen 2\n'; }
@test "empty" { check $'' 3 $''; }
@test "no-words" { check $' ... ,!? \n' 3 $''; }
@test "case" { check $'Word word WORD wOrD' 1 $'word 4\n'; }
@test "ties" { check $'pear fig apple fig pear apple' 3 $'apple 2\nfig 2\npear 2\n'; }
@test "fold-before-sort" { check $'Zebra apple' 2 $'apple 1\nzebra 1\n'; }
@test "n-zero" { check $'a b c' 0 $''; }
@test "n-above-count" { check $'a b a' 10 $'a 2\nb 1\n'; }
@test "non-ascii" { check $'café naïve café 日本語 naïve café' 3 $'café 3\nnaïve 2\n日本語 1\n'; }
@test "code-point-order" { check $'f é e' 3 $'e 1\nf 1\né 1\n'; }
@test "apostrophe" { check $'don\'t stop, don\'t' 3 $'don 2\nt 2\nstop 1\n'; }
@test "digits" { check $'route 66 and route 66a 66' 3 $'66 2\nroute 2\n66a 1\n'; }
@test "separators" { check $'tab\there\r\nunder_score-dash' 10 $'dash 1\nhere 1\nscore 1\ntab 1\nunder 1\n'; }
References
- The Python Standard Library, collections, Counter objects, Counter; most_common
- The Python Standard Library, Built-in Types, str.casefold; str.lower
- The Python HOWTOs, Sorting Techniques, Key Functions; Sort Stability and Complex Sorts
- The Python Language Reference, Expressions, 6.10.1 Value comparisons (strings, sequences)
- MDN Web Docs, Character class escape, Description (\w)
- MDN Web Docs, String.prototype.localeCompare, Description
- MDN Web Docs, Intl.Segmenter.prototype.segment, Return value (isWordLike)
- Ecma International, ECMA-262, ECMAScript Language Specification, 7.2.12 IsLessThan (strings compare by code unit)
- Java SE 25 API, java.lang.String, toLowerCase(), toLowerCase(Locale), compareTo(String)
- Java SE 25 API, java.util.regex.Pattern, Predefined character classes (\w); UNICODE_CHARACTER_CLASS; Characters (\x{h...h})
- Java SE 25 API, java.util.Map, merge
- .NET API reference, Enumerable.ThenBy, Remarks
- .NET documentation, Best practices for comparing strings in .NET, String comparisons that use the current culture
- .NET API reference, String.ToLowerInvariant, Remarks
- The Go Programming Language Specification, For statements with range clause (iteration order over maps)
- Go standard library, package strings, FieldsFunc, ToLower, Compare
- Go standard library, package slices, SortFunc
- The Rust Standard Library, std::collections::HashMap, entry; iter (arbitrary order)
- cppreference.com, std::unordered_map, Description; operator[]
- The Rust Standard Library, primitive type slice, sort_unstable_by
- cppreference.com, tolower, Parameters; Return value
- cppreference.com, std::char_traits::eq, std::char_traits::lt
- The Open Group, POSIX.1-2024, qsort, Description
- The Open Group, POSIX.1-2024, uniq, Description; Options (-c)
- The Open Group, POSIX.1-2024, tr, Options (-c); Operands (ranges, octal escapes)
- The Open Group, POSIX.1-2024, sort, Description; Options (-k, -n, -r); Environment Variables (LC_COLLATE)
- Unicode Standard Annex, 4 Word Boundaries
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
The native tests pass in 9 of 10 languages in this build.
Tag 71X4H9 Edit this page History Report an error Markdown