v9.1.1
Menu

Document Term Matrix

easyFREEText RepresentationNLP 1: Foundations

Given a list of documents, build a document-term matrix where each row represents a document and each column represents a unique word from the vocabulary.

The vocabulary should be sorted alphabetically. Each cell contains the count of that word in that document. All words should be lowercased.

Input: docs, a list of n document strings (words separated by spaces).

Output: Return the matrix as a list of lists of integers, one row per document in input order (the tests print each row).

Example

Input
2
the cat sat
the dog sat
Output
[1, 0, 1, 1]
[0, 1, 1, 1]
Reasoning
  • Input: docs holds 2 documents, "the cat sat" and "the dog sat". Words are separated by spaces.
  • Columns (vocabulary): the distinct lowercase words across both documents are cat, dog, sat and the. In alphabetical order they fix 4 columns: cat, dog, sat, the. Shared words (sat, the) get one column.
  • Rows (counts): entry cdjc_{dj} is how many times vocabulary word jj occurs in document dd. Document 1 has cat, sat and the once each and no dog, giving [1, 0, 1, 1]. Document 2 has no cat and one each of dog, sat, the, giving [0, 1, 1, 1].
  • Output shape: a 2×42 \times 4 matrix of integers, one row per document in input order. Every row has length 4 even though each document only uses 3 words, so the zeros mark words a document lacks.
  • Notice: counts are not capped at 1. For "a a a" the word a scores 3, and each row sums to its document's word count: 1+0+1+1=31 + 0 + 1 + 1 = 3.

Constraints

  • 1 ≤ n ≤ 10
  • Words are separated by spaces
  • Convert all words to lowercase
  • Vocabulary sorted alphabetically
  • Output each row as a Python list of integers

Learn this in

More from NLP 1: Foundations

solution.py

Test results

Sign in to run your code against the test cases.