Skip to main content
 首页 » 编程设计

python之如何从列表中制作特征向量

2025年05月04日9lhb25

我是 python 的新手。实际上我有一个词袋中的火车数据。火车数据的每一行都是一篇文章。训练数据的标签在另一个文件中,每个 i 标签等于训练数据中的第 i 篇文章。我在火车数据上做了词干分析,也删除了停用词。输出是每篇文章(行)的单词列表。现在我想提取它的特征向量,然后在我的 python 中的 KNN 分类器中使用它。我不知道该怎么做!我感谢任何快速回答。这是我所做的代码:

  import nltk 
  from nltk.corpus import stopwords 
  from nltk import stem 
  stemmer=stem.PorterStemmer() 
 
 
  with open('data.txt')as file: 
  while 1: 
      line=file.readline().split() 
      filtered_words = [w for w in line if not w in stopwords.words('english')] 
      documents = [stemmer.stem(line) for line in filtered_words] 
 
      print(documents) 
 
 
      if not line: 
         break 
      pass 

请您参考如下方法:

看看 Scikit-learn 的 CountVectorizer或 TfIdfVectorizer .这些可以将文档列表(这些是 token 列表,如您的示例所示)作为其输入,并返回一个特征矩阵:

from sklearn.feature_extraction.text import CountVectorizer 
count_vect = CountVectorizer() 
X_train_counts = count_vect.fit_transform(your_list_of_documents) 

您可以在 Working with Text Data Tutorial 中找到更多信息.