标签:index word Tokenizer keras text sequence UNKOWN texts print
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后的词表:
我 1
们 2
都 3
有 4
一 5
个 6
家 7
名 8
字 9
叫 10
中 11
国 12
====================
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
标签:index,word,Tokenizer,keras,text,sequence,UNKOWN,texts,print 来源: https://blog.csdn.net/qq_16949707/article/details/110562364
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。