Es scheint knifflige Dinge zu bekommen genau das gleiche zwischen nltk
und tm
auf den Vorverarbeitungsschritten, so denke ich, die Der beste Ansatz ist, rpy2
zu verwenden, um die Vorverarbeitung in R auszuführen und die Ergebnisse in Python zu ziehen:
import rpy2.robjects as ro
preproc = [x[0] for x in ro.r('''
tweets = read.csv("tweets.csv", stringsAsFactors=FALSE)
library(tm)
library(SnowballC)
corpus = Corpus(VectorSource(tweets$Tweet))
corpus = tm_map(corpus, tolower)
corpus = tm_map(corpus, removePunctuation)
corpus = tm_map(corpus, removeWords, c("apple", stopwords("english")))
corpus = tm_map(corpus, stemDocument)''')]
Dann können Sie es in scikit-learn
laden - das einzige, was Sie tun müssen, werde die Dinge zwischen dem CountVectorizer
und dem DocumentTermMatrix
anzupassen ist hinsichtlich der Länge zu entfernen, weniger als 3:
from sklearn.feature_extraction.text import CountVectorizer
def mytokenizer(x):
return [y for y in x.split() if len(y) > 2]
# Full document-term matrix
cv = CountVectorizer(tokenizer=mytokenizer)
X = cv.fit_transform(preproc)
X
# <1181x3289 sparse matrix of type '<type 'numpy.int64'>'
# with 8980 stored elements in Compressed Sparse Column format>
# Sparse terms removed
cv2 = CountVectorizer(tokenizer=mytokenizer, min_df=0.005)
X2 = cv2.fit_transform(preproc)
X2
# <1181x309 sparse matrix of type '<type 'numpy.int64'>'
# with 4669 stored elements in Compressed Sparse Column format>
wir überprüfen diese mit R übereinstimmt:
tweets = read.csv("tweets.csv", stringsAsFactors=FALSE)
library(tm)
library(SnowballC)
corpus = Corpus(VectorSource(tweets$Tweet))
corpus = tm_map(corpus, tolower)
corpus = tm_map(corpus, removePunctuation)
corpus = tm_map(corpus, removeWords, c("apple", stopwords("english")))
corpus = tm_map(corpus, stemDocument)
dtm = DocumentTermMatrix(corpus)
dtm
# A document-term matrix (1181 documents, 3289 terms)
#
# Non-/sparse entries: 8980/3875329
# Sparsity : 100%
# Maximal term length: 115
# Weighting : term frequency (tf)
sparse = removeSparseTerms(dtm, 0.995)
sparse
# A document-term matrix (1181 documents, 309 terms)
#
# Non-/sparse entries: 4669/360260
# Sparsity : 99%
# Maximal term length: 20
# Weighting : term frequency (tf)
Wie Sie die Anzahl der gespeicherten Elemente und Bedingungen finden können, genau jetzt zwischen den beiden Ansätzen entsprechen.
Verwenden nltk für die Verarbeitung natürlicher Sprache in Python. – ramcdougal
@ramcdougal: So viel habe ich gesammelt, aber ich kämpfe mit der Dokumentation. – orome
Schauen Sie sich das [Tutorial] (http://nbviewer.ipython.org/urls/gist.githubusercontent.com/kljensen/9662971/raw/4628ed3a1d27b84a3c56e46d87146c1d08267893/NewHaven.io+NLP+tutorial.ipynb?create=1) an. Es umfasst Tokenisierung, Stoppwörter und Stemming. – ramcdougal