为什么我在PySpark中进行RegexTokenizer转换会得到与所需模式相反的内容?

问题描述 投票:0回答:1

当我使用pyspark.ml.feature中的RegexTokenizer对数据框中的句子列进行标记以查找所有单词字符时,我得到的结果与python re 包用于同一句子。这是示例代码:

from pyspark.sql import SparkSession
from pyspark.ml.feature import RegexTokenizer
spark = SparkSession.builder \
        .master("local") \
        .appName("Word list") \
        .getOrCreate()

df = spark.createDataFrame(data = [["Hi there, I have a question about RegexTokenizer, Could you 
                           please help me..."]], schema = ["Sentence"])

regexTokenizer = RegexTokenizer(inputCol="Sentence", outputCol="letters", pattern="\\w")
df = regexTokenizer.transform(df)
df.first()['letters']

这将提供以下输出:

[' ', ', ', ' ', ' ', ' ', ' ', ' ', ', ', ' ', ' ', ' ', ' ', '...']

另一方面,如果我在同一句子上使用re模块,并使用相同的模式来匹配字母,请在此处使用此代码:

import re
sentence = "Hi there, I have a question about RegexTokenizer, could you 
                           please help me..."
letters_list = re.findall("\\w", sentence)
print(letters_list)

我根据正则表达式模式获得所需的输出:

['H', 'i', 't', 'h', 'e', 'r', 'e', 'I', 'h', 'a', 'v', 'e', 'a', 
'q', 'u', 'e', 's', 't', 'i', 'o', 'n', 'a', 'b', 'o', 'u', 't', 
'R', 'e', 'g', 'e', 'x', 'T', 'o', 'k', 'e', 'n', 'i', 'z', 'e', 
'r', 'c', 'o', 'u', 'l', 'd', 'y', 'o', 'u', 'p', 'l', 'e', 'a', 
's', 'e', 'h', 'e', 'l', 'p', 'm', 'e']

我还发现我需要在pySpark中使用\ W而不是\ w来解决此问题。为什么会有这种差异?还是我误解了RegexTokenizerpattern参数的用法?

regex pyspark tokenize
1个回答
0
投票
根据documentation on RegexTokenizer的说法,在创建时,它具有一个称为gaps的参数。在一种模式下,正则表达式匹配间隙(true,是默认值),在另一种模式下,它匹配标记(而非间隙,false)。

尝试将其手动设置为所需的值:在您的情况下为gaps = false

© www.soinside.com 2019 - 2024. All rights reserved.