Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions measurements/word_count/word_count.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
26 changes: 26 additions & 0 deletions tests/test_word_count.py
Original file line number Diff line number Diff line change
@@ -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 _"])