from sklearn.feature_extraction.text import CountVectorizer corpus = ['apple banana apple', 'banana orange'] vectorizer = CountVectorizer() X = vectorizer.fit_transform(corpus) result = X.toarray() vocab = vectorizer.get_feature_names_out() print(vocab) print(result)
The CountVectorizer creates a vocabulary sorted alphabetically: ['apple', 'banana', 'orange']. It counts how many times each word appears in each document. The first document has 'apple' twice and 'banana' once, no 'orange'. The second document has 'banana' once and 'orange' once.
The unique words are 'cat', 'dog', and 'mouse'. So the vocabulary size is 3.
Stop words like 'the' are removed. Remaining words are 'cat', 'sat', 'dog', 'barked'. Vocabulary is sorted alphabetically.
'apple' appears in the first and third documents, so document frequency is 2.
The corpus contains an integer 123, which causes CountVectorizer to raise a TypeError because it expects strings.
