首页 > 解决方案 > 文本分析,R 中的 DocumentTermMatrix 翻译成 Python

问题描述

我在 R 中有以下代码,并在 Python 中寻找等价的代码。我想要做的是从文本中取出单词,清理它们(删除标点符号、降低、去除空格等),并以矩阵格式从它们中创建变量,可用于预测模型。

text<- c("amazing flight",
         "got there early",
         "great prices on flights??")
mydata_1<- data.frame(text)

library(tm)
corpus<- Corpus(DataframeSource(mydata_1))
corpus<- tm_map(corpus, content_transformer(tolower))
corpus<- tm_map(corpus, removePunctuation)
corpus<- tm_map(corpus, removeWords, stopwords("english"))
corpus<- tm_map(corpus, stripWhitespace)

dtm_1<- DocumentTermMatrix(corpus)
final_output<- as.matrix(dtm_1)

输出如下所示,其中“amazing”、“early”等词现在是我可以在模型中使用的二进制输入变量:

Docs   amazing early flight flights got great prices
 1       1     0      1       0      0     0      0
 2       0     1      0       0      1     0      0
 3       0     0      0       1      0     1      1

如何在 Python 中做到这一点?

标签: pythonrtexttext-processing

解决方案


我找到了答案。Python 中的DocumentTermMatrix等效项称为CountVectorizer

text= ["amazing flight","got there early","great prices on flights??"]

from sklearn.feature_extraction.text import CountVectorizer
import pandas as pd

vectorizer= CountVectorizer() 
X= vectorizer.fit_transform(text)
Y= vectorizer.get_feature_names()
final_output= pd.DataFrame(X.toarray(),columns=Y)

这给出了以下结果:

       amazing  early  flight  flights  got  great  on  prices  there
0      1        0      1       0        0    0      0   0       0
1      0        1      0       0        1    0      0   0       1
2      0        0      0       1        0    1      1   1       0

推荐阅读