假设我在桌面上有一个文件夹,里面有不同的.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_*')]