前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Keras实现文本预处理

Keras实现文本预处理

作者头像
致Great
发布2018-08-02 14:28:15
5530
发布2018-08-02 14:28:15
举报
文章被收录于专栏:程序生活程序生活
代码语言:javascript
复制
from keras.preprocessing.text import text_to_word_sequence
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences

text1 = "今天 北京 下 暴雨 了"
text2 = "我 今天 打车 回家"
texts = [text1, text2]

print(text_to_word_sequence(text1))  # 按空格分割语料
# ['今天', '北京', '下', '暴雨', '了']

tokenizer = Tokenizer(num_words=10)
tokenizer.fit_on_texts(texts)
print(tokenizer.document_count) # 处理文档的数量
# 2
print(tokenizer.word_counts) # 词频字典,按词频从大到小排序
# OrderedDict([('今天', 2), ('北京', 1), ('下', 1), ('暴雨', 1), ('了', 1), ('我', 1), ('打车', 1), ('回家', 1)])
print(tokenizer.word_docs) # 保存每个word出现的文档的数量
# {'了': 1, '暴雨': 1, '北京': 1, '下': 1, '今天': 2, '打车': 1, '回家': 1, '我': 1}
print(tokenizer.word_index) # 给每个词唯一id
# {'今天': 1, '北京': 2, '下': 3, '暴雨': 4, '了': 5, '我': 6, '打车': 7, '回家': 8}
print(tokenizer.index_docs) # 保存word的id出现的文档的数量
# {5: 1, 4: 1, 2: 1, 3: 1, 1: 2, 7: 1, 8: 1, 6: 1}

# 将序列填充到maxlen长度
print(pad_sequences([[1,2,3],[4,5,6]],maxlen=10,padding='pre')) # 在序列前填充
# [[0 0 0 0 0 0 0 1 2 3]
# [0 0 0 0 0 0 0 4 5 6]]
print(pad_sequences([[1,2,3],[4,5,6]],maxlen=10,padding='post')) # 在序列后填充
# [[1 2 3 0 0 0 0 0 0 0]
# [4 5 6 0 0 0 0 0 0 0]]
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018.07.16 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档