python - 文本分析,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 中做到这一点?
解决方案
我找到了答案。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
推荐阅读
- javascript - 我有与按钮相同类的框。单击按钮时,应将文本框添加到相应的框中
- html - 是否可以创建一个始终将用户带到其国家/地区网站的链接?
- vba - 操作 TextRange 时 Mac 与 Windows 的差异与行/段落
- laravel - niklasravnsborg / laravel-pdf 中的波斯数字
- python - 我无法将 bs4 输出导出到文件
- python - 从 c++ 中使用 cppyy 读取 char16_t* 字符串
- python - 类方法局部变量可以修改类变量吗?
- c++ - 从临时对象的成员数据问题中引用初始化
- c - C:将值排序到静态列表中
- javascript - 如何选择警报框的文本?