mindspore.dataset.text.RegexTokenizer

class mindspore.dataset.text.RegexTokenizer(delim_pattern, keep_delim_pattern='', with_offsets=False)[源代码]

根据正则表达式对字符串进行分词。

有关支持的正则表达式的模式,请参阅 https://unicode-org.github.io/icu/userguide/strings/regexp.html

说明

Windows平台尚不支持 RegexTokenizer

参数:
  • delim_pattern (str) - 以正则表达式表示的分隔符,字符串将被正则匹配的分隔符分割。

  • keep_delim_pattern (str, 可选) - 如果被 delim_pattern 匹配的字符串也能被 keep_delim_pattern 匹配,就可以此分隔符作为标记(token)保存。 默认值: '' (空字符),即分隔符不会作为输出标记保留。

  • with_offsets (bool, 可选) - 是否输出各Token在原字符串中的起始和结束偏移量。默认值: False

异常:
  • TypeError - 参数 delim_pattern 的类型不是str。

  • TypeError - 参数 keep_delim_pattern 的类型不是str。

  • TypeError - 参数 with_offsets 的类型不是bool。

支持平台:

CPU

样例:

>>> import mindspore.dataset as ds
>>> import mindspore.dataset.text as text
>>>
>>> # Use the transform in dataset pipeline mode
>>> numpy_slices_dataset = ds.NumpySlicesDataset(data=['Welcome  |,  To  |,  BeiJing!'],
...                                              column_names=["text"])
>>>
>>> # 1) If with_offsets=False, default output is one column {["text", dtype=str]}
>>> delim_pattern = r"[ |,]"
>>> tokenizer_op = text.RegexTokenizer(delim_pattern, with_offsets=False)
>>> numpy_slices_dataset = numpy_slices_dataset.map(operations=tokenizer_op)
>>> for item in numpy_slices_dataset.create_dict_iterator(num_epochs=1, output_numpy=True):
...     print(item["text"])
['Welcome' 'To' 'BeiJing!']
>>>
>>> # 2) If with_offsets=True, then output three columns {["token", dtype=str],
>>> #                                                     ["offsets_start", dtype=uint32],
>>> #                                                     ["offsets_limit", dtype=uint32]}
>>> numpy_slices_dataset = ds.NumpySlicesDataset(data=['Welcome  |,  To  |,  BeiJing!'],
...                                              column_names=["text"])
>>> tokenizer_op = text.RegexTokenizer(delim_pattern, with_offsets=True)
>>> numpy_slices_dataset = numpy_slices_dataset.map(
...     operations=tokenizer_op,
...     input_columns=["text"],
...     output_columns=["token", "offsets_start", "offsets_limit"])
>>> for item in numpy_slices_dataset.create_dict_iterator(num_epochs=1, output_numpy=True):
...     print(item["token"], item["offsets_start"], item["offsets_limit"])
['Welcome' 'To' 'BeiJing!'] [ 0 13 21] [ 7 15 29]
>>>
>>> # Use the transform in eager mode
>>> data = 'Welcome     To   BeiJing!'
>>> output = text.RegexTokenizer(delim_pattern="To", keep_delim_pattern="To", with_offsets=True)(data)
>>> print(output)
(array(['Welcome     ', 'To', '   BeiJing!'], dtype='<U12'),
array([ 0, 12, 14], dtype=uint32), array([12, 14, 25], dtype=uint32))
教程样例: