基于词汇表和正则表达式对文档进行矢量化

Vectorize document based on vocabulary AND regex

我正在尝试使用 sklearn 的 CountVectorizer 训练文本分类器。问题是我的训练文档有很多特定于文档的标记。因此,例如,CountVectorizer.fit_transform 方法可以很好地处理一些常规英语单词,但也有一些格式适合正则表达式的标记:'\w\d\d\w\w\d',例如 'd84ke2'.就像现在一样,fit_transform 方法只会采用 'd84ke2' 的面值并将其用作特征。

我希望能够使用那些与特定正则表达式匹配的特定标记作为它们自己的特征,并将常规英语单词保留为它们自己的特征,因为创建诸如 'd84ke2' 之类的特征将毫无用处因为这不会在任何其他文件中再次出现。

我还没有找到执行此操作的方法,更不用说 "best" 方法了。下面是我的代码示例,您可以在其中看到标记 'j64ke2'、'r32kl4'、'w35kf9' 和 'e93mf9' 都变成了它们自己的特征。为了清楚起见,我重复一遍:我想基本上将这些功能浓缩为一个并保留其他功能。

docs = ['the quick brown j64ke2 jumped over the lazy dogs r32kl4.', 
        'an apple a day keeps the w35kf9 away', 
        'you got the lions share of the e93mf9']

import numpy as np
# define target and target_names  
target_names = ['zero', 'one', 'two']
target = np.array([0, 1, 2])

# Create message bunch. 
from sklearn.utils import Bunch
doc_info = Bunch(data=docs, target=target, target_names=target_names)


# Vectorize training data
from sklearn.feature_extraction.text import CountVectorizer
count_vect = CountVectorizer()
count_vect.fit(doc_info.data)

vocab = count_vect.vocabulary_
vocab_keys = list(vocab.keys())
#vocab_vals = list(vocab.values())

X_train_counts = count_vect.transform(doc_info.data)
X = X_train_counts.toarray()        
import pandas as pd
df = pd.DataFrame(X, columns=vocab_keys)

yatu的评论很好解决。通过为每个匹配的正则表达式替换一个词,我能够在将文档提供给 CountVectorizer 之前清理文档。