我們需要開始思考如何將文本集合轉化為可量化的東西。最簡單的方法是考慮詞頻。
我將盡量嘗試不使用NLTK和Scikits-Learn包。我們首先使用Python講解一些基本概念。
基本詞頻
首先,我們回顧一下如何得到每篇文檔中的詞的個數(shù):一個詞頻向量。
#examples taken from here: http://stackoverflow.com/a/1750187 mydoclist = ['Julie loves me more than Linda loves me','Jane likes me more than Julie loves me','He likes basketball more than baseball'] #mydoclist = ['sun sky bright', 'sun sun bright'] from collections import Counter for doc in mydoclist: tf = Counter() for word in doc.split(): tf[word] +=1 print tf.items()[('me', 2), ('Julie', 1), ('loves', 2), ('Linda', 1), ('than', 1), ('more', 1)][('me', 2), ('Julie', 1), ('likes', 1), ('loves', 1), ('Jane', 1), ('than', 1), ('more', 1)][('basketball', 1), ('baseball', 1), ('likes', 1), ('He', 1), ('than', 1), ('more', 1)]
這里我們引入了一個新的Python對象,被稱作為Counter。該對象只在Python2.7及更高的版本中有效。Counters非常的靈活,利用它們你可以完成這樣的功能:在一個循環(huán)中進行計數(shù)。
根據(jù)每篇文檔中詞的個數(shù),我們進行了文檔量化的第一個嘗試。但對于那些已經(jīng)學過向量空間模型中“向量”概念的人來說,第一次嘗試量化的結果不能進行比較。這是因為它們不在同一詞匯空間中。
我們真正想要的是,每一篇文件的量化結果都有相同的長度,而這里的長度是由我們語料庫的詞匯總量決定的。
import string #allows for format() def build_lexicon(corpus): lexicon = set() for doc in corpus: lexicon.update([word for word in doc.split()]) return lexicon def tf(term, document): return freq(term, document) def freq(term, document): return document.split().count(term) vocabulary = build_lexicon(mydoclist) doc_term_matrix = []print 'Our vocabulary vector is [' + ', '.join(list(vocabulary)) + ']'for doc in mydoclist: print 'The doc is "' + doc + '"' tf_vector = [tf(word, doc) for word in vocabulary] tf_vector_string = ', '.join(format(freq, 'd') for freq in tf_vector) print 'The tf vector for Document %d is [%s]' % ((mydoclist.index(doc)+1), tf_vector_string) doc_term_matrix.append(tf_vector) # here's a test: why did I wrap mydoclist.index(doc)+1 in parens? it returns an int... # try it! type(mydoclist.index(doc) + 1) print 'All combined, here is our master document term matrix: 'print doc_term_matrix
我們的詞向量為[me, basketball, Julie, baseball, likes, loves, Jane, Linda, He, than, more]
文檔”Julie loves me more than Linda loves me”的詞頻向量為:[2, 0, 1, 0, 0, 2, 0, 1, 0, 1, 1]
文檔”Jane likes me more than Julie loves me”的詞頻向量為:[2, 0, 1, 0, 1, 1, 1, 0, 0, 1, 1]
新聞熱點
疑難解答