荣誉版主
- 积分
- 978
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2010-2-23
- 最后登录
- 1970-1-1
|
本帖最后由 YZDH 于 2021-2-12 18:26 编辑 . 1point3acres
27. Bag of words
For a collection of documents, find the vocabulary and the bag of word matrix.
Example:
Input:
doc1 = 'The quick brown fox jumps over the lazy wolf'
doc2 = 'The fast brown fox jumps over the lazy dog'. .и
doc3 = 'The speedy brown fox hops over the lazy dog'
Output:
(['brown',
'dog',
'fast',. 1point3acres
'fox',
'hops',. From 1point 3acres bbs
'jumps',
'lazy',.1point3acres
'over',
'quick',
'speedy',
'the',
'wolf'],
[[1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 2, 1],
[1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 2, 0],
[1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 2, 0]]).1point3acres
- from collections import Counter
- def bag_of_words(docs):
- """
- Args:.
- - docs: collection of documents
-
- Returns:
- - vocab: the vocabulary from the docs
- - result: the bag og word matrix
- """
-
. - # helper function to get bag of words for each doc in the docs
- def bow_helper(doc, vocab):
- doc_word_counts = Counter(doc)
- doc_vec = [0]*len(vocab)
-
- for idx, word in enumerate(vocab):
- if word in doc_word_counts:
- doc_vec[idx] += doc_word_counts[word]
-
- return doc_vec
-
- # get vocabulary of the docs
- vocab = sorted(list(set([word for doc in docs for word in doc])))
- result = []
-
- # loop over each doc to get the bag of word matrix
- for doc in docs:. Waral dи,
- result.append(bow_helper(doc, vocab))
-
- return vocab, result
复制代码
- doc1 = 'The quick brown fox jumps over the lazy wolf'
- doc2 = 'The fast brown fox jumps over the lazy dog'
- doc3 = 'The speedy brown fox hops over the lazy dog'. 1point3acres
- docs = [[word.lower() for word in doc.split()] for doc in documents] # tokenize
- docs. 1point 3 acres
- . .и
- # [['the', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'wolf'],
- # ['the', 'fast', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog'],
- # ['the', 'speedy', 'brown', 'fox', 'hops', 'over', 'the', 'lazy', 'dog']]
- bag_of_words(docs)-baidu 1point3acres
- # (['brown',
- # 'dog',
- # 'fast',-baidu 1point3acres
- # 'fox', ..
- # 'hops',
- # 'jumps',
- # 'lazy',
- # 'over',
- # 'quick',. .и
- # 'speedy',
- # 'the',-baidu 1point3acres
- # 'wolf'],. 1point3acres.com
- # [[1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 2, 1],-baidu 1point3acres
- # [1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 2, 0],
- # [1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 2, 0]])
复制代码
. 1point3acres
.--
补充内容 (2021-2-19 02:51):
第二段代码补上:documents = [doc1, doc2, doc3]
感谢 wujiayikelly |
|