python中精确复制R文本预处理

2024-07-08 08:16:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望使用Python以与在R中相同的方式预处理文档的语料库。例如,给定一个初始语料库corpus,我希望以一个预处理的语料库结束,该语料库与使用以下R代码生成的语料库相对应:

library(tm)
library(SnowballC)

corpus = tm_map(corpus, tolower)
corpus = tm_map(corpus, removePunctuation)
corpus = tm_map(corpus, removeWords, c("myword", stopwords("english")))
corpus = tm_map(corpus, stemDocument)

在Python中有没有一种简单或直接(最好是预先构建的)方法来实现这一点?有没有办法确保完全相同的结果?在


例如,我想预处理

@Apple ear pods are AMAZING! Best sound from in-ear headphones I've ever had!

进入

ear pod amaz best sound inear headphon ive ever


Tags: 文档map方式librarycorpus代码生成tm语料库
2条回答

CountVectorizer和{}可以按照docs中的描述进行自定义。特别是,您需要编写一个自定义标记器,它是一个接受文档并返回一个术语列表的函数。使用NLTK:

import nltk.corpus.stopwords
import nltk.stem

def smart_tokenizer(doc):
    doc = doc.lower()
    doc = re.findall(r'\w+', doc, re.UNICODE)
    return [nltk.stem.PorterStemmer().stem(term)
            for term in doc
            if term not in nltk.corpus.stopwords.words('english')]

演示:

^{pr2}$

(我链接到的示例实际上使用一个类来缓存lemmatizer,但是函数也可以工作。)

在预处理步骤中,在nltk和{}之间获得完全相同的结果似乎很棘手,因此我认为最好的方法是使用rpy2在R中运行预处理并将结果拉入python:

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)''')]

然后,可以将其加载到scikit-learn中,要使CountVectorizer和{}之间的匹配,只需删除长度小于3的项:

^{pr2}$

让我们用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)
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)

正如您所看到的,现在两种方法之间存储的元素和术语的数量完全匹配。在

相关问题 更多 >

    热门问题