如何使用scikit-learn加载和处理.txt文件?

假设我在桌面上有一个文件夹,里面有不同的.txt文件。它们看起来像这样。

文件1:

('this', 'is'), ('a', 'very'),....., ('large', '.txt'), ('file', 'with'), ('lots', 'of'), ('words', 'like'), ('this', 'i'), ('would', 'like'), ('to', 'create'), ('a', 'matrix'),'LABEL_1'

文件N:

('this', 'is'), ('a', 'another'),....., ('large', '.txt'), ('file', 'with'), ('lots', 'of'), ('words', 'like'), ('this', 'i'), ('would', 'like'), ('to', 'create'), ('a', 'matrix'),'LABEL_N'

根据文档,scikit-learn提供了load_files,我可以使用哈希技巧进行向量化,如下所示:

from sklearn.feature_extraction.text import FeatureHasherfrom sklearn.svm import SVCtraining_data = [[('string1', 'string2'), ('string3', 'string4'),                  ('string5', 'string6'), 'POS'],                 [('string1', 'string2'), ('string3', 'string4'), 'NEG']]feature_hasher_vect = FeatureHasher(input_type ='string')X = feature_hasher_vect.transform(((' '.join(x) for x in sample)                                        for sample in training_data))print X.toarray()

输出:

[[ 0.  0.  0. ...,  0.  0.  0.] [ 0.  0.  0. ...,  0.  0.  0.]]

我如何对整个.txt文件夹进行向量化(应用上述相同过程)使用load_files()或其他任何方法?


回答:

我不熟悉scikit-learn,它可能有更好的方法,但如果你展示的文件格式是正确的,你可以使用以下相对简单的函数来实现你描述的操作:

import astimport globimport osdef my_load_files(folder, pattern):    pathname = os.path.join(folder, pattern)    for filename in glob.glob(pathname):        with open(filename) as file:            yield ast.literal_eval(file.read())text_folder = 'C:/Users/username/Desktop/Samples'print [[' '.join(x) for x in sample]                        for sample in my_load_files(text_folder, 'File_*')]

注意: 由于每个文件末尾都有一个标签(和你的training_data一样),你可能想使用以下替代方法,这样可以将标签排除在传递给feature_hasher_vect.transform()方法的内容之外:

print [[' '.join(x) for x in sample[:-1]]                        for sample in my_load_files(text_folder, 'File_*')]

Related Posts

Keras Dense层输入未被展平

这是我的测试代码: from keras import…

无法将分类变量输入随机森林

我有10个分类变量和3个数值变量。我在分割后直接将它们…

如何在Keras中对每个输出应用Sigmoid函数?

这是我代码的一部分。 model = Sequenti…

如何选择类概率的最佳阈值?

我的神经网络输出是一个用于多标签分类的预测类概率表: …

在Keras中使用深度学习得到不同的结果

我按照一个教程使用Keras中的深度神经网络进行文本分…

‘MatMul’操作的输入’b’类型为float32,与参数’a’的类型float64不匹配

我写了一个简单的TensorFlow代码,但不断遇到T…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注