实现子词分词器
在这一步中,你将实现一个子词分词器函数,该函数使用贪婪最长匹配优先算法对英语单词执行字符级分词。此函数还会从输入字符串中删除所有符号,包括空格。
在代码编辑器中打开 subword_tokenizer.py
文件。此文件包含 subword_tokenizer()
函数的框架。你的任务是填写该函数中缺失的部分。
该函数应满足以下要求:
- 函数应接受一个字符串作为输入。此函数接收一个包含英语字符、数字和标点符号的字符串。该字符串已提供给你,你不能更改字符串的内容。
- 函数应返回分词结果作为一个列表。
以下是 subword_tokenizer()
函数的完整代码:
import re
def subword_tokenizer(text, vocab) -> list:
"""
根据提供的词汇表将输入文本分词为子词。
参数:
- text (str):要分词的输入文本。
- vocab (list):包含子词的词汇表列表。
返回:
- list:子词标记列表。
"""
def is_in_vocab(word) -> bool:
"""
检查给定的词是否在词汇表中。
参数:
- word (str):要检查的词。
返回:
- bool:如果词在词汇表中,则返回 True,否则返回 False。
"""
return word in vocab
def find_longest_match(word) -> tuple:
"""
在词汇表中找到给定词的最长匹配子词。
参数:
- word (str):要找到匹配项的词。
返回:
- tuple:一个包含最长匹配子词和词的剩余部分的元组。
"""
for i in range(len(word), 0, -1):
subword = word[:i]
if is_in_vocab(subword):
return subword, word[i:]
return "[UNK]", ""
tokens = []
## 移除非字母数字字符并将文本拆分为单词
words = re.findall(r"\b\w+\b", text)
for word in words:
while word:
subword, remaining = find_longest_match(word)
tokens.append(subword)
word = remaining
return tokens
if __name__ == "__main__":
## 示例用法:
vocab = [
"I",
"studied",
"in",
"LabEx",
"for",
"1",
"0",
"days",
"and",
"completed",
"the",
"course",
]
text = "I studied in LabEx for 10 days and completed the TensorFlow Serving course."
tokenization_result = subword_tokenizer(text, vocab)
print(tokenization_result)