tensorflow——tf.contrib.learn.preprocessing.VocabularyProcessor用法

主要构建语料集中的词典,以及把中文序列转化为词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]]



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值