【问题标题】:R, after utf8 filtering still weird charactersR,经过utf8过滤后仍然奇怪的字符
【发布时间】:2017-04-29 09:50:31
【问题描述】:

我对 R 很陌生,但我需要对推文进行一些文本挖掘。我正在尝试清理语料库,以便只有 UTF8 字符。我使用下面的函数来过滤掉非 UTF 字符。

#setup with own twitter key's and access tokens
library(twitteR)
library(tm)

setup_twitter_oauth(consumer_key,consumer_secret,access_token,access_secret)
keyword = "#circulatieplan"
sinceDate = "2017-3-1"
tweets = searchTwitter(keyword,n = 300,lang = 'nl',since = sinceDate)
tweets_df = twListToDF(tweets)
tweets_df
View(tweets_df)

text = tweets_df$text
corpus = Corpus(VectorSource(text))
corpus <- tm_map(corpus, content_transformer(function(x) iconv(enc2utf8(x), sub = "byte")))

corpus_clean <- tm_map(corpus, tolower)

之后我尝试将其全部设为小写,但随后出现一些输入错误。

Error in FUN(content(x), ...) : invalid input 'Elke Sleurs gehoord op de radio. Dan viel Siegi precies nog mee. #schizo ������������' in 'utf8towcs'

我的猜测是过滤没有完美完成,该函数无法将“�”更改为小写。

我并不完全了解 utf 过滤的工作原理以及它的全部含义。有没有更好的功能或者我该如何解决这个错误。

编辑:
查看原始数据后,我发现有些推文包含的 utf 字符长度超过 2 个字节。
包含 tis 问题的推文的 tweetid:858280532039397379
数据:

"Elke Sleurs gehoord op de radio. Dan viel Siegi precies nog mee. #schizo \xed\xa0\xbd\xed\xb8\xb3\xed\xa0\xbd\xed\xb9\x84 #gent #circulatieplan",

然后我不成功地尝试使用正则表达式删除它们中的所有内容。正则表达式是错误的还是不能在语料库对象上使用正则表达式?

corpus <- tm_map(corpus, content_transformer(function(x) gsub(x, pattern = "(\\)\\w+", replacement = "")))

【问题讨论】:

  • 不是tolower的问题,是编码的问题。你能发布一个 repodex 并实际调用 twitter api 吗?
  • 我不知道你对 repodex 的意思是什么,是我提出的查询吗?我更新了代码,您可以在其中看到我的 twitter 搜索参数。
  • 我说的是一个可重现的例子。它基本上只是您提供给论坛的代码,以便我们可以重现您遇到的问题。你快到了:运行你的代码会抛出错误:get_oauth_sig() 中的错误:尚未为此会话注册 OAuth
  • 所以只需发布完整的代码,这样我们就可以获得与您相同的输出
  • 很可能,该库无法处理包含表情符号等的 long utf8 (0xe0,0xf0,0xf8 组)。你有原始 json 正文(或推文 id ?)

标签: r twitter utf-8 text-mining


【解决方案1】:

我找到了一种过滤表情符号的方法。经过大量搜索,我发现有一个函数可以在编码之间转换字符向量。 iconv documentation

...
text = tweets_df$text    
# remove emoticons
text <- sapply(text,function(row) iconv(row, "latin1", "ASCII", sub=""))
corpus = Corpus(VectorSource(text))
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-04
    • 2011-04-07
    • 2014-02-12
    • 1970-01-01
    • 1970-01-01
    • 2019-10-29
    • 1970-01-01
    • 2014-01-27
    相关资源
    最近更新 更多