【问题标题】:R tm package invalid input in 'utf8towcs'R tm 包在“utf8towcs”中输入无效
【发布时间】:2012-03-27 02:15:26
【问题描述】:

我正在尝试使用 R 中的 tm 包来执行一些文本分析。我绑定了以下内容:

require(tm)
dataSet <- Corpus(DirSource('tmp/'))
dataSet <- tm_map(dataSet, tolower)
Error in FUN(X[[6L]], ...) : invalid input 'RT @noXforU Erneut riesiger (Alt-)�lteppich im Golf von Mexiko (#pics vom Freitag) http://bit.ly/bw1hvU http://bit.ly/9R7JCf #oilspill #bp' in 'utf8towcs'

问题是某些字符无效。我想在 R 中或在导入文件进行处理之前从分析中排除无效字符。

我尝试使用 iconv 将所有文件转换为 utf-8 并排除任何无法转换为的文件,如下所示:

find . -type f -exec iconv -t utf-8 "{}" -c -o tmpConverted/"{}" \; 

正如这里指出的Batch convert latin-1 files to utf-8 using iconv

但我仍然遇到同样的错误。

我将不胜感激。

【问题讨论】:

    标签: r utf-8 iconv text-mining


    【解决方案1】:

    我的 mac 也遇到了同样的问题,通过下面的解决方案解决了。

    raw_data <- read.csv(file.choose(), stringsAsFactors = F,  encoding="UTF-8")
    
    raw_data$textCol<- iconv(raw_data$textCol, "ASCII", "UTF-8", sub="byte")
    
    data_corpus <- VCorpus(VectorSource(raw_data$textCol))
    
    corpus_clean = tm_map(data_corpus, function(x) iconv(x, to='UTF-8-MAC', sub='byte'))
    
    corpus_clean <- tm_map(data_corpus, content_transformer(tolower))
    

    【讨论】:

      【解决方案2】:

      我经常遇到这个问题,而这篇 Stack Overflow 帖子总是首先出现。我之前用过顶级解决方案,但是它可以去掉字符并用垃圾替换它们(比如将it’s转换为it’s)。

      我发现实际上有一个更好的解决方案!如果您安装了stringi 软件包,您可以将tolower() 替换为stri_trans_tolower(),然后一切正常。

      【讨论】:

        【解决方案3】:

        我可以通过使用这行代码将数据转换回纯文本格式来修复它

        corpus &lt;- tm_map(corpus, PlainTextDocument)

        感谢用户https://stackoverflow.com/users/4386239/paul-gowder

        在这里回复他

        https://stackoverflow.com/a/29529990/815677

        【讨论】:

          【解决方案4】:

          以前的建议对我不起作用。我调查了更多,发现在以下https://eight2late.wordpress.com/2015/05/27/a-gentle-introduction-to-text-mining-using-r/

          #Create the toSpace content transformer
          toSpace <- content_transformer(function(x, pattern) {return (gsub(pattern," ",
          x))})
          # Apply it for substituting the regular expression given in one of the former answers by " "
          your_corpus<- tm_map(your_corpus,toSpace,"[^[:graph:]]")
          
          # the tolower transformation worked!
          your_corpus <- tm_map(your_corpus, content_transformer(tolower))
          

          【讨论】:

            【解决方案5】:

            我认为现在很清楚问题是因为tolower无法理解的表情符号

            #to remove emojis
            dataSet <- iconv(dataSet, 'UTF-8', 'ASCII')
            

            【讨论】:

              【解决方案6】:

              Chad 的解决方案对我不起作用。我将它嵌入到一个函数中,它给出了一个关于 iconv 需要一个向量作为输入的错误。所以,我决定在创建语料库之前进行转换。

              myCleanedText <- sapply(myText, function(x) iconv(enc2utf8(x), sub = "byte"))
              

              【讨论】:

                【解决方案7】:

                以上答案都不适合我。解决此问题的唯一方法是删除所有非图形字符 (http://stat.ethz.ch/R-manual/R-patched/library/base/html/regex.html)。

                代码就是这么简单

                usableText=str_replace_all(tweets$text,"[^[:graph:]]", " ") 
                

                【讨论】:

                • 这应该被标记为解决方案。它有效,并且多年来一直很受欢迎,但 OP 并没有坚持将其标记为正确。
                • 作为base r的替代方案,你可以试试:usableText &lt;- iconv(tweets$text, "ASCII", "UTF-8", sub="")
                【解决方案8】:

                我一直在 Mac 上运行此程序,令我沮丧的是,我必须找出犯规记录(因为这些是推文)才能解决。由于下次不保证记录相同,所以我使用了以下函数

                tm_map(yourCorpus, function(x) iconv(x, to='UTF-8-MAC', sub='byte'))
                

                如上所述。

                效果很好

                【讨论】:

                  【解决方案9】:

                  官方常见问题解答似乎不适用于我的情况:

                  tm_map(yourCorpus, function(x) iconv(x, to='UTF-8-MAC', sub='byte'))
                  

                  最后我使用了 for & Encoding 函数:

                  for (i in 1:length(dataSet))
                  {
                    Encoding(corpus[[i]])="UTF-8"
                  }
                  corpus <- tm_map(dataSet, tolower)
                  

                  【讨论】:

                    【解决方案10】:

                    我刚刚遇到了这个问题。碰巧您使用的是运行 OSX 的机器吗?我现在并且似乎已经将问题追溯到在此操作系统上编译 R 的字符集的定义(请参阅https://stat.ethz.ch/pipermail/r-sig-mac/2012-July/009374.html

                    我看到的是使用常见问题解答中的解决方案

                    tm_map(yourCorpus, function(x) iconv(enc2utf8(x), sub = "byte"))
                    

                    给了我这个警告:

                    Warning message:
                    it is not known that wchar_t is Unicode on this platform 
                    

                    我追踪到了enc2utf8 函数。坏消息是,这是我的底层操作系统而不是 R 的问题。

                    这就是我所做的解决方法:

                    tm_map(yourCorpus, function(x) iconv(x, to='UTF-8-MAC', sub='byte'))
                    

                    这会强制 iconv 在 macintosh 上使用 utf8 编码,并且无需重新编译即可正常工作。

                    【讨论】:

                      【解决方案11】:

                      如果可以忽略无效输入,您可以使用 R 的错误处理。例如:

                        dataSet <- Corpus(DirSource('tmp/'))
                        dataSet <- tm_map(dataSet, function(data) {
                           #ERROR HANDLING
                           possibleError <- tryCatch(
                               tolower(data),
                               error=function(e) e
                           )
                      
                           # if(!inherits(possibleError, "error")){
                           #   REAL WORK. Could do more work on your data here,
                           #   because you know the input is valid.
                           #   useful(data); fun(data); good(data);
                           # }
                        }) 
                      

                      这里还有一个例子:http://gastonsanchez.wordpress.com/2012/05/29/catching-errors-when-using-tolower/

                      【讨论】:

                        【解决方案12】:

                        使用以下步骤:

                        # First you change your document in .txt format with encoding UFT-8
                        library(tm)
                        # Set Your directoryExample ("F:/tmp").
                        dataSet <- Corpus(DirSource ("/tmp"), readerControl=list(language="english)) # "/tmp" is your directory. You can use any language in place of English whichever allowed by R.
                        dataSet <- tm_map(dataSet, tolower)
                        
                        Inspect(dataSet)
                        

                        【讨论】:

                          【解决方案13】:

                          这是来自 tm 常见问题:

                          它将用字符串替换 yourCorpus 中不可转换的字节 显示他们的十六进制代码。

                          我希望这对我有帮助。

                          tm_map(yourCorpus, function(x) iconv(enc2utf8(x), sub = "byte"))
                          

                          http://tm.r-forge.r-project.org/faq.html

                          【讨论】:

                            【解决方案14】:

                            这是tm 包(123)的常见问题。

                            一种非R 的修复方法是在将文本加载到R(或使用gsub)之前,使用文本编辑器查找并替换文本中的所有花哨字符(即带有变音符号的字符)在R)。例如,您将搜索并替换 Öl-Teppich 中 O-umlaut 的所有实例。 Others 已经成功了(我也成功了),但是如果你有数千个单独的文本文件,这显然是不好的。

                            对于R的解决方案,我发现使用VectorSource而不是DirSource似乎可以解决问题:

                            # I put your example text in a file and tested it with both ANSI and 
                            # UTF-8 encodings, both enabled me to reproduce your problem
                            #
                            tmp <- Corpus(DirSource('C:\\...\\tmp/'))
                            tmp <- tm_map(dataSet, tolower)
                            Error in FUN(X[[1L]], ...) : 
                              invalid input 'RT @noXforU Erneut riesiger (Alt-)Öl–teppich im Golf von Mexiko (#pics vom Freitag) http://bit.ly/bw1hvU http://bit.ly/9R7JCf #oilspill #bp' in 'utf8towcs'
                            # quite similar error to what you got, both from ANSI and UTF-8 encodings
                            #
                            # Now try VectorSource instead of DirSource
                            tmp <- readLines('C:\\...\\tmp.txt') 
                            tmp
                            [1] "RT @noXforU Erneut riesiger (Alt-)Öl–teppich im Golf von Mexiko (#pics vom Freitag) http://bit.ly/bw1hvU http://bit.ly/9R7JCf #oilspill #bp"
                            # looks ok so far
                            tmp <- Corpus(VectorSource(tmp))
                            tmp <- tm_map(tmp, tolower)
                            tmp[[1]]
                            rt @noxforu erneut riesiger (alt-)öl–teppich im golf von mexiko (#pics vom freitag) http://bit.ly/bw1hvu http://bit.ly/9r7jcf #oilspill #bp
                            # seems like it's worked just fine. It worked for best for ANSI encoding. 
                            # There was no error with UTF-8 encoding, but the Ö was returned 
                            # as ã– which is not good
                            

                            但这似乎有点幸运的巧合。必须有更直接的方法。请让我们知道什么对您有用!

                            【讨论】:

                            • 感谢您的回复本!出于某种原因,对我来说失败的同一行代码现在可以工作了。我不知道这是否是另一个幸运的巧合 :) 我没有更改任何内容,只是重新运行它,这次它可以正常工作。
                            猜你喜欢
                            • 2017-10-16
                            • 1970-01-01
                            • 1970-01-01
                            • 1970-01-01
                            • 2018-05-03
                            • 1970-01-01
                            • 2013-07-07
                            • 1970-01-01
                            • 1970-01-01
                            相关资源
                            最近更新 更多