主要构建语料集中的词典,以及把中文序列转化为词id序列
函数
tf.contrib.learn.preprocessing.VocabularyProcessor(max_document_length, min_frequency=0, vocabulary=None, tokenizer_fn=None)
参数:
max_document_length: 文档的最大长度。如果文本的长度大于最大长度,那么它会被剪切,反之则用0填充。
min_frequency: 词频的最小值,出现次数小于最小词频则不会被收录到词表中。
vocabulary: CategoricalVocabulary 对象。
tokenizer_fn:分词函数
用法示例:
from tensorflow.contrib import learn
import tensorflow as tf
import numpy as np
import jieba
test_text =['盼望着,盼望着,东风来了,春天的脚步近了。',
'一切都像刚睡醒的样子,欣欣然张开了眼。山朗润起来了,水涨起来了,太阳的脸红起来了。',
'桃树、杏树、梨树,你不让我,我不让你,都开满了花赶趟儿。']
#分词及去掉标点符号
def tokenizer(document):
tokenizer_document = []
for text in document:
content = jieba.cut(text)
stoplist = [',', '。', '、']
outstr = ""
for word in content:
if word not in stoplist:
outstr+=word
outstr+=" "
tokenizer_document.append(outstr)
return tokenizer_document
# 分词后的文本
tokenizer_document = tokenizer(test_text)
# ['盼望着 盼望着 东风 来 了 春天 的 脚步 近 了 ', '一切 都 像 刚 睡醒 的 样子 欣欣然 张开 了 眼 山朗润 起来 了 水 涨起来 了 太阳 的 脸红 起来 了 ', '桃树 杏树 梨树 你 不让 我 我 不让 你 都 开满 了 花 赶趟儿 ']
max_document_length = max([len(text.split(" ")) for text in tokenizer_document])
# 构建词典
vocab_processor = learn.preprocessing.VocabularyProcessor(max_document_length,min_frequency=0,vocabulary=None,tokenizer_fn=None)
# 创建词汇表
vocab_processor.fit(tokenizer_document)
# 将文本转为词ID序列,未知或填充用的词ID为0
x = np.array(list(vocab_processor.fit_transform(tokenizer_document)))
print(x)
# [[ 1 1 2 3 4 5 6 7 8 4 0 0 0 0 0 0 0 0 0 0 0 0 0]
# [ 9 10 11 12 13 6 14 15 16 4 17 18 19 4 20 21 4 22 6 23 19 4 0]
# [24 25 26 27 28 29 29 28 27 10 30 4 31 32 0 0 0 0 0 0 0 0 0]]