keras preprocessing中的Tokenizer与sequence使用解读

4 篇文章 0 订阅

1. 代码

import jieba
from keras.preprocessing.text import Tokenizer
from keras.preprocessing import sequence

def cut_text(text, type = 'char'):
    """将文本按不同方式切词,以空格作为分割"""
    # print(text)
    if type == 'char':
        return ' '.join(list(text))
    elif type == 'jieba':
        seg_list = jieba.cut(text)  # 默认是精确模式
        return ' '.join(seg_list)
    else:
        raise NotImplemented


texts = ["我们都有一个家","名字叫中国"]
tok = Tokenizer(num_words=10)
tok.fit_on_texts([cut_text(_, type = 'char') for _ in texts])


print("="*20)
print("Tokenizer fit后的词表:")
index_2_word = dict()
for ii, (word, index) in enumerate(tok.word_index.items()):
    print(word, index)
    index_2_word[index] = word

print("="*20)
print("texts_to_sequences 有啥作用:")
tokens = tok.texts_to_sequences([cut_text(_, type = 'char') for _ in texts])
for t in tokens:
    print(t)
    print([index_2_word[_] for _ in t])


print("="*20)
print("pad_sequences 有啥作用:")
index_2_word[0] = 'UNKOWN'
tokens_pad = sequence.pad_sequences(tokens, maxlen=50, padding='pre', truncating='pre')
for t in tokens_pad:
    print(t)
    print([index_2_word[_] for _ in t])

2. 输出


====================
Tokenizer fit后的词表:123456789101112
====================
texts_to_sequences 有啥作用:
[1, 2, 3, 4, 5, 6, 7]
['我', '们', '都', '有', '一', '个', '家']
[8, 9]
['名', '字']
====================
pad_sequences 有啥作用:
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
 0 0 0 0 0 0 1 2 3 4 5 6 7]
['UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', '我', '们', '都', '有', '一', '个', '家']
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
 0 0 0 0 0 0 0 0 0 0 0 8 9]
['UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', '名', '字']

Process finished with exit code 0


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值