Skip to main content
 首页 » 编程设计

python之文本挖掘和 NLP : from R to Python

2025年05月04日10fff_TT

首先声明一下,我是python新手。目前,我正在将大量 R 代码“翻译”成 Python 并一路学习。这个问题与这个有关 replicating R in Python (在那里他们实际上建议使用 rpy2 来包装它,出于学习目的我想避免这样做)。

在我的例子中,不是在 python 中完全复制 R,我实际上想学习一种“pythonian”的方式来做我在这里描述的事情:

我有一个长向量(40000 个元素),其中每个元素都是一段文本,例如:

> descr 
[1] "dress Silver Grey Printed Jersey Dress 100% cotton" 
[2] "dress Printed Silk Dress 100% Silk Effortless style."                                                                                                                                                                                     
[3] "dress Rust Belted Kimono Dress 100% Silk relaxed silhouette, mini length"  

然后我对其进行预处理,例如:

# customized function to remove patterns in strings. used later within tm_map 
rmRepeatPatterns <- function(str) gsub('\\b(\\S+?)\\1\\S*\\b', '', str, 
                                   perl = TRUE) 
 
# process the corpus 
pCorp <- Corpus(VectorSource(descr)) 
pCorp <- tm_map(pCorp, content_transformer(tolower)) 
pCorp <- tm_map(pCorp, rmRepeatPatterns) 
pCorp <- tm_map(pCorp, removeStopWords) 
pCorp <- tm_map(pCorp, removePunctuation) 
pCorp <- tm_map(pCorp, removeNumbers) 
pCorp <- tm_map(pCorp, stripWhitespace) 
pCorp <- tm_map(pCorp, PlainTextDocument) 
 
# create a term document matrix (control functions can also be passed here) and a table: word - freq 
Tdm1 <- TermDocumentMatrix(pCorp) 
freq1 <- rowSums(as.matrix(Tdm1)) 
dt <- data.table(terms=names(freq1), freq=freq1) 
 
# and perhaps even calculate a distance matrix (transpose because Dist operates on a row basis) 
D <- Dist(t(as.matrix(Tdm1))) 

总的来说,我想知道在 python 中执行此操作的适当方法,主要是文本处理。

例如,我可以删除此处描述的停用词和数字 get rid of StopWords and Numbers (尽管对于这样一个简单的任务来说似乎需要做很多工作)。但是我看到的所有选项都意味着处理文本本身而不是映射整个语料库。换句话说,它们意味着通过 descr 向量“循环”。

无论如何,我们将不胜感激。此外,我还有一堆自定义函数,例如 rmRepeatPatterns,因此学习如何映射这些函数将非常有用。

提前感谢您的宝贵时间。

请您参考如下方法:

看起来“这样做”涉及对字符串列表进行一些正则表达式替换。 Python 在这个领域提供了比 R 更强大的功能。以下是我如何应用您的 rmRepeatedPatterns 替换,使用列表理解:

pCorp = [ re.sub(r'\b(\S+?)\1\S*\b', '', line) for line in pCorp ] 

如果你想把它包装在一个函数中:

def rmRepeatedPatterns(line): 
    return re.sub(r'\b(\S+?)\1\S*\b', '', line) 
 
pCorp = [ rmRepeatedPatterns(line) for line in pCorp ] 

Python 还有一个 map 运算符,您可以将其与您的函数一起使用:

pCorp = map(rmRepeatedPatterns, pCorp) 

但是列表推导式更强大、更富表现力和更灵活;如您所见,您可以应用简单的替换而无需将它们隐藏在函数中。

补充说明:

  1. 如果您的数据集很大,您还可以学习使用生成器而不是列表理解;本质上,它们让您可以按需生成元素,而不是创建大量中间列表。

  2. Python 有一些运算符,例如 map,但是如果您要进行大量矩阵操作,您应该阅读 numpy,它提供了更多的 R - 类似的体验。

编辑:再次查看示例 R 脚本后,我将按照以下方式进行剩余的清理工作,即。获取您的行列表,将其转换为小写,删除标点符号和数字(特别是:所有不是英文字母的内容),并删除停用词。

# Lower-case, split into words, discard everything that's not a letter 
tok_lines = [ re.split(r"[^a-z]+", line.lower()) for line in pCorp ] 
# tok_lines is now a list of lists of words 
 
stopwordlist = nltk.corpus.stopwords.words("english") # or any other list 
stopwords = set(w.lower() for w in stopwordlist) 
cleantoks = [ [ t for t in line if t not in stopwords ]  
                                        for line in tok_lines ] 

我不建议使用 question you link to 中提出的任何一种解决方案.在集合中查找东西比在大列表中查找要快很多,而且我会使用推导式而不是 filter()。