-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathdoc2bow.py
38 lines (32 loc) · 1.32 KB
/
doc2bow.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#!/usr/bin/python
# -*- coding: utf-8 -*-
from gensim import corpora
from collections import defaultdict
documents = ["Human machine interface for lab abc computer applications",
"A survey of user opinion of computer system response time",
"The EPS user interface management system",
"System and human system engineering testing of EPS",
"Relation of user perceived response time to error measurement",
"The generation of random binary unordered trees",
"The intersection graph of paths in trees",
"Graph minors IV Widths of trees and well quasi ordering",
"minors A survey A survey A"]
# word split
doc_text_list = []
for d in documents:
doc_text_list.append( d.split(' ') )
# get dict
dic = corpora.Dictionary(doc_text_list)
print(dic)# Dictionary(45 unique tokens: ['System', 'Graph', 'machine', 'quasi', 'A']...)
# get bag of word features
corpus = [dic.doc2bow(text) for text in doc_text_list]
print(corpus)# corpus is the word:word_count for each sentence
'''
such as the last sentence [(8, 3), (12, 2), (41, 1)]
'''
# store corpus
corpora.MmCorpus.serialize('corpus.mm', corpus) # store to disk, for later use
del corpus
# load corpus
corpus = corpora.MmCorpus('corpus.mm')
print(corpus[-1])