From 25f04495aa84afd314f92bfcb30210d01cb604bb Mon Sep 17 00:00:00 2001 From: Hani Mohanad <164931686+snygginghani@users.noreply.github.com> Date: Sat, 28 Nov 2026 05:35:49 +0300 Subject: [PATCH] Count uncapped words without building a document matrix --- measurements/word_count/word_count.py | 13 +++++++++++++ tests/test_word_count.py | 26 ++++++++++++++++++++++++++ 2 files changed, 39 insertions(+) create mode 100644 tests/test_word_count.py diff --git a/measurements/word_count/word_count.py b/measurements/word_count/word_count.py index 36d2cda6b..e1733a0b3 100644 --- a/measurements/word_count/word_count.py +++ b/measurements/word_count/word_count.py @@ -63,6 +63,19 @@ def _info(self): def _compute(self, data, max_vocab=None): """Returns the number of unique words in the input data""" count_vectorizer = CountVectorizer(max_features=max_vocab) + if max_vocab is None: + analyze = count_vectorizer.build_analyzer() + vocabulary = set() + word_count = 0 + for document in data: + words = analyze(document) + word_count += len(words) + vocabulary.update(words) + + if not vocabulary: + raise ValueError("empty vocabulary; perhaps the documents only contain stop words") + return {"total_word_count": count_vectorizer.dtype(word_count), "unique_words": len(vocabulary)} + document_matrix = count_vectorizer.fit_transform(data) word_count = document_matrix.sum() unique_words = document_matrix.shape[1] diff --git a/tests/test_word_count.py b/tests/test_word_count.py new file mode 100644 index 000000000..e64e96d6d --- /dev/null +++ b/tests/test_word_count.py @@ -0,0 +1,26 @@ +from pathlib import Path + +import pytest + +import evaluate + + +@pytest.fixture +def word_count(): + pytest.importorskip("sklearn") + path = Path(__file__).resolve().parents[1] / "measurements" / "word_count" + return evaluate.load(str(path), module_type="measurement", keep_in_memory=True) + + +@pytest.mark.parametrize( + ("max_vocab", "total", "unique"), + [(None, 6, 3), (2, 5, 2)], +) +def test_word_count(word_count, max_vocab, total, unique): + result = word_count.compute(data=["Café, café! a BEER.", "Beer café tea."], max_vocab=max_vocab) + assert result == {"total_word_count": total, "unique_words": unique} + + +def test_word_count_rejects_empty_vocabulary(word_count): + with pytest.raises(ValueError, match="empty vocabulary"): + word_count.compute(data=["a !", "I _"])