首页 > 解决方案 > R 中的 tolower(txt) 非字符参数错误(用于文本挖掘)

问题描述

因此,作为初学者,我正在尝试使用 R 语言进行简单的文本挖掘 (NLP)。

我使用tm_map函数预处理了我的数据并检查了它,所有的标点符号和数字都被删除了。tolower()我还使用函数将文本文档转换为小写。效果很好。

但是在创建文档矩阵时,我遇到了一个错误问题:

tolower(txt) 中的错误:非字符参数

这个错误是什么以及如何继续这个错误?这与UTF8有关吗?任何线索将不胜感激。

docs <- tm_map(docs, removePunctuation) 
inspect(docs[1]) 

for(j in seq(docs)) { 
  docs[[j]] <- gsub("\n", " ", docs[[j]]) 
} 

docs <- tm_map(docs, removeNumbers) 
docs <- tm_map(docs, content_transformer(tolower)) 
docs <- tm_map(docs, removeWords, stopwords("english")) 
docs <- tm_map(docs, stripWhitespace) 

这一切都很好,我的文本文档(只是一本电子书)被转换为小写字母,没有空格、数字等。很好,下一步返回错误。

# returns the above error. 
dtm <- DocumentTermMatrix(docs)

标签: rnlpdata-sciencetext-mining

解决方案


问题不在于将您的语料库变成DocumentTermMatrix. 问题在于你的for循环。它将你的语料库变成一个字符列表。

如果你想这样使用gsub,你需要使用该content_transformer功能。

# removes the need of the for loop and keeps everything in a corpus.
docs <- tm_map(docs, content_transformer(function(x) gsub("\n", " ", x)))

这消除了循环的需要并保持一切应有的状态。在这一行之后,您可以毫无问题地运行其余代码。


推荐阅读