为什么我在 PySpark 中的 RegexTokenizer 转换给出了与所需模式相反的结果?

Why my RegexTokenizer transformation in PySpark gives me the opposite of the required pattern?

当我使用 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来解决这个问题。为什么会有这种差异?或者我误解了 pattern 参数在 RegexTokenizer?

中的用法

根据 documentation on RegexTokenizer 所说,在创建时它有一个名为 gaps 的参数。在一种模式下,正则表达式匹配间隙(true 并且是默认值),在另一种模式下它匹配标记(不是间隙,false)。

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