RegexTokenizer:正则表达式分词器
class pyspark.ml.feature.RegexTokenizer(minTokenLength=1, gaps=True, pattern=’\s+’, inputCol=None, outputCol=None, toLowercase=True)
一个基于正则表达式的分词器,它通过使用提供的正则表达式模式(Java语言)来拆分文本(默认)或重复匹配正则表达式(如果 gaps 为 false)来提取令牌。 可选参数还允许使用最小长度过滤令牌。 它返回一个可以为空的字符串数组。
**minTokenLength *= Param(parent=‘undefined’, name=‘minTokenLength’, doc=‘minimum token length (>= 0)’)
gaps = Param(parent=‘undefined’, name=‘gaps’, doc='正则表达式是否在间隙上拆分 (True) 或匹配标记 (False))*
01.创建数据
from pyspark.sql import SparkSession
spark = SparkSession.builder.appName("RegexTokenizer").master("local[*]").getOrCreate()
#%%
df = spark.createDataFrame([("Optional parameters also allow filtering tokens",)], ["text"])
df.head(1)
输出结果:
[Row(text='Optional parameters also allow filtering tokens')]
02.设置参数minTokenLength=1,转换数据:
from pyspark.ml.feature import RegexTokenizer
reTokenizer = RegexTokenizer(inputCol="text", outputCol="words",minTokenLength=1)
reTokenizer.transform(df).head()
输出结果:
Row(text='Optional parameters also allow filtering tokens', words=['optional', 'parameters', 'also', 'allow', 'filtering', 'tokens'])
03.修改参数minTokenLength=6,重新转换模型
reTokenizer.setParams(minTokenLength=6).transform(df).head(1)
输出结果:
[Row(text='Optional parameters also allow filtering tokens', words=['optional', 'parameters', 'filtering', 'tokens'])]
05.添加参数gaps,对比输出结果
reTokenizer.setParams(gaps=True,minTokenLength=6).transform(df).head(1)
输出结果:
[Row(text=‘Optional parameters also allow filtering tokens’, words=[‘optional’, ‘parameters’, ‘filtering’, ‘tokens’])]
reTokenizer.setParams(gaps=False,minTokenLength=6).transform(df).head(1)
输出结果:[Row(text=‘Optional parameters also allow filtering tokens’, words=[])]