【问题标题】:Removing non-English text from Corpus in R using tm()使用 tm() 从 R 中的语料库中删除非英文文本
【发布时间】:2013-08-11 18:54:38
【问题描述】:

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

假设我的 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 字符,那么这就是诀窍:sapply(words, function(row) iconv(row, "latin1", "ASCII", sub=""))(from here)。但这会给您留下缺少字符的单词片段。如果您想删除非英语单词,那么您可以使用非 ASCII 字符对单词进行子集化,将它们添加到您的停用词列表中,并在删除停用词时将其删除。
  • 我确实看过那个帖子,但它打开了不得不将语料库更改为另一个对象的大门?在语料库上运行此命令会产生:Error in UseMethod("tm_map", x) : no applicable method for 'tm_map' applied to an object of class "c('matrix', 'character')"
  • 您可以将sapply 的输出转换回语料库,如下所示:dat1 &lt;- sapply(words, function(row) iconv(row, "latin1", "ASCII", sub="")) 然后再转换回语料库:words1 &lt;- Corpus(VectorSource(dat1))
  • 此外,您应该能够通过在任何文本编辑器中打开 txt 文件并在底部添加一些空白行,然后在 R 中保存、关闭和重新加载来修复您的第一条警告消息跨度>
  • 如果您在这里没有找到答案,请尝试Corpus Linguistics with R 邮件列表中的人

标签: r tm


【解决方案1】:

这是一种在制作语料库之前删除带有非 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

【讨论】:

    【解决方案2】:

    您也可以使用“stringi”包。

    使用上面的例子:

    library(stringi)
    dat <- "Special,  satisfação, Happy, Sad, Potential, für"
    stringi::stri_trans_general(dat, "latin-ascii")
    

    输出:

    [1] "Special,  satisfacao, Happy, Sad, Potential, fur"  
    

    【讨论】:

      猜你喜欢
      • 2020-05-12
      • 2015-08-03
      • 2017-05-08
      • 1970-01-01
      • 1970-01-01
      • 2014-12-31
      • 2018-08-16
      • 2019-10-26
      • 2018-10-28
      相关资源
      最近更新 更多