介绍
gensim能很方便的把文档转换成计算机能处理的形式,一般文档集合要先产生词典dictionary,词典就是包括文档集所有词的集合,每个词都在词典里有一个唯一的位置,就用位置来表示这个词。之后每一篇文档就能表示成(词id,词频)这种形式,用于后面的处理。
实战
from gensim import corpora
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",
"Graph minors A survey"]
# remove common words and tokenize
stoplist = set('for a of the and to in'.split())
texts = [[word for word in document.lower().split() if word not in stoplist] for document in documents]
# remove words that appear only once
from collections import defaultdict
frequency = defaultdict(int)
for text in texts:
for token in text:
frequency[token] += 1
texts = [[token for token in text if frequency[token] > 1] for text in texts]
from pprint import pprint
pprint(type(texts))
pprint(texts)
# 将corpus里面的词做成词典
dictionary = corpora.Dictionary(texts)
print(dictionary)
# 词典里面的词与id对应关系
print(dictionary.token2id)
# store the dictionary, for future reference
# dictionary.save('/tmp/deerwester.dict')
# 遍历文本,词和词频。
# 将新来文本转换成词典的词和位置向量,词典没有的词忽略
new_doc = "Human computer interaction"
new_vec = dictionary.doc2bow(new_doc.lower().split())
print(new_vec) # the word "interaction" does not appear in the dictionary and is ignored
# 函数doc2bow()简单地计算每个不同单词的词频,将该单词转换为其整数字id,并将结果作为稀疏向量返回
corpus = [dictionary.doc2bow(text) for text in texts]
# corpora.MmCorpus.serialize('/tmp/deerwester.mm', corpus) # store to disk, for later use
pprint(corpus)
输出