是否有类似于 sklearn.PolynomialFeatures 但用于字符串的 python 函数?

Is there a python function similar to sklearn.PolynomialFeatures but for strings?

sklearn.PolynomialFeatures 函数生成向量的多项式和交互特征。例如:

>>> X = [[1,2,3]]
>>> G = sklearn.PolynomialFeatures(degree = 3, interaction_only = True, bias = False)
>>> G.fit_transform(X)
>>> print(G)
>>>
array([[1., 2., 3., 2., 3., 6., 6.]])

是否有适用于字符串的等效函数,以便如果输入数组是 X = [['a','b','c']] 该函数将输出 array([['a','b','c','ab','ac','bc','abc']]) 并且该函数可以采用任何输入向量? 如果不存在这样的功能,您是否知道如何创建它?

看起来你正在寻找 superset of the input list of strings. This is fairly easy to implement using itertools,但如果你想要 fit/transform 结构(允许你在管道中包含转换器) ,您可以定义自己的继承自 TransformerMixin 的转换器。否则只需使用 transform 方法中包含的代码:

from sklearn.base import TransformerMixin
from itertools import combinations, chain

class NSuperset(TransformerMixin):
    def __init__(self, n):
        self.n = n

    def fit(self, X):
        return self

    def transform(self, X):
        superset = [[''.join(c) for x in X for c in combinations(x, r=i)] 
                    for i in range(1,self.n+1)]
        return list(chain.from_iterable(superset))

ss = NSuperset(n=3)

X = [['a','b','c']]
ss.fit_transform(X)
# ['a', 'b', 'c', 'ab', 'ac', 'bc', 'abc']