首页 > 解决方案 > 如何使用 Tokenizer 函数 tensorflow 对标点符号进行标记

问题描述

我使用 as 中的Tokenizer()函数tensorflow.keras.preprocessing.text

from tensorflow.keras.preprocessing.text import Tokenizer
s = ["The quick brown fox jumped over the lazy dog."]
t = Tokenizer()
t.fit_on_texts(s)
print(t.word_index)

输出 :

{'the': 1, 'quick': 2, 'brown': 3, 'fox': 4, 'jumped': 5, 'over': 6, 'lazy': 7, 'dog': 8}

Tokenizer 函数不包括标点符号。如何标记标点符号?( .,在这个例子中。)

标签: pythontensorflowkerasnlptokenize

解决方案


一种可能性是将标点符号与带有空格的单词分开。我使用预处理功能来做到这一点pad_punctuationTokenizer在此之后我申请filter=''

import re
import string
from tensorflow.keras.preprocessing.text import Tokenizer

def pad_punctuation(s): return re.sub(f"([{string.punctuation}])", r' \1 ', s)

S = ["The quick brown fox jumped over the lazy dog."]
S = [pad_punctuation(s) for s in S]

t = Tokenizer(filters='')
t.fit_on_texts(S)
print(t.word_index)

结果:

{'the': 1, 'quick': 2, 'brown': 3, 'fox': 4, 'jumped': 5, 'over': 6, 'lazy': 7, 'dog': 8, '.': 9}

pad_punctuation功能对所有标点均有效


推荐阅读