使用 tm() 从 R 中的语料库中删除非英语文本

标签 r tm

我正在使用 tm()wordcloud() 在 R 中进行一些基本的数据挖掘,但遇到了困难,因为我的文件中有非英文字符数据集(尽管我尝试根据背景变量过滤掉其他语言。

假设我的 TXT 文件(在 TextWrangler 中保存为 UTF-8)中的某些行如下所示:

Special
satisfação
Happy
Sad
Potential für

然后我将 txt 文件读入 R:

words <- Corpus(DirSource("~/temp", encoding = "UTF-8"),readerControl = list(language = "lat"))

这会产生警告消息:

Warning message:
In readLines(y, encoding = x$Encoding) :
  incomplete final line found on '/temp/file.txt'

但由于这是一个警告,而不是错误,所以我继续前进。

words <- tm_map(words, stripWhitespace)
words <- tm_map(words, tolower)

这会产生错误:

Error in FUN(X[[1L]], ...) : invalid input 'satisfa��o' in 'utf8towcs'

我愿意寻找在 TextWrangler 或 R 中过滤掉非英语字符的方法;无论如何都是最方便的。感谢您的帮助!

最佳答案

以下是在制作语料库之前删除包含非 ASCII 字符的单词的方法:

# remove words with non-ASCII characters
# assuming you read your txt file in as a vector, eg. 
# dat <- readLines('~/temp/dat.txt')
dat <- "Special,  satisfação, Happy, Sad, Potential, für"
# convert string to vector of words
dat2 <- unlist(strsplit(dat, split=", "))
# find indices of words with non-ASCII characters
dat3 <- grep("dat2", iconv(dat2, "latin1", "ASCII", sub="dat2"))
# subset original vector of words to exclude words with non-ASCII char
dat4 <- dat2[-dat3]
# convert vector back to a string
dat5 <- paste(dat4, collapse = ", ")
# make corpus
require(tm)
words1 <- Corpus(VectorSource(dat5))
inspect(words1)

A corpus with 1 text document

The metadata consists of 2 tag-value pairs and a data frame
Available tags are:
  create_date creator 
Available variables in the data frame are:
  MetaID 

[[1]]
Special, Happy, Sad, Potential

关于使用 tm() 从 R 中的语料库中删除非英语文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18153504/

相关文章:

R:删除字符串中的部分单词

r - tm 合并语料库列表

r - 具有不同列名称的 for 循环中的 left_join

r - 如何有效地排序R中字符串中的字符?

r - 计算嵌套小标题 R 中的比例?

r - 将数组从 matlab 导入 R

c++ - 复制结构 tm

r - 如何在选项卡上获得 Shiny 的通知图标

r - 如何制作 1 亿条推文的 R tm 语料库?

用于预测分析的 R tm 包。如何对新文档进行分类?