【问题标题】:How to load_files and process a .txt file with scikit-learn?如何使用 scikit-learn 加载和处理 .txt 文件?
【发布时间】:2015-02-19 00:06:04
【问题描述】:

假设我在桌面的一个文件夹中有不同的 .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'

documentation,scikit-learn 提供load_files,我可以使用散列技巧进行矢量化,如下所示:

from sklearn.feature_extraction.text import FeatureHasher
from sklearn.svm import SVC

training_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.]]

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

【问题讨论】:

    标签: python python-2.7 machine-learning scikit-learn nltk


    【解决方案1】:

    我不熟悉skikit-learn,它可能有更好的东西,但如果文件采用显示的格式,您可以按照您描述的方式使用相对简单的方法,如下面的函数所示:

    import ast
    import glob
    import os
    
    def 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_*')]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-15
      • 2019-05-06
      • 2018-07-07
      • 2012-10-15
      • 1970-01-01
      • 1970-01-01
      • 2014-02-17
      • 2013-01-29
      相关资源
      最近更新 更多