介绍
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"]
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]
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)
dictionary = corpora.Dictionary(texts)
print(dictionary)
print(dictionary.token2id)
new_doc =
"Human computer interaction"
new_vec = dictionary.doc2bow(new_doc.
lower().
split())
print(new_vec)
corpus = [dictionary.doc2bow(
text)
for text in texts]
pprint(corpus)
输出