我正在使用我的R脚本使用Twitter REST API 1.1(user_timeline.json(。我收集了大量的推文。
不幸的是,文本包含许多特殊字符,例如n
,^
或单个。到目前为止,在通过
fromJSON
(jsonlite 包(导入它们之前,我能够用 str_replace_all 或 gsub 替换它们:
correctJSON <- function(string) {
string <- str_replace_all(string, pattern = perl('\\(?![tn"])'), replacement = " ")
string <- str_replace_all(string, pattern = "n", replacement = " ")
string <- str_replace_all(string, pattern = "r", replacement = " ")
string <- str_replace_all(string, pattern = "\^", replacement = " ")
return(string)
}
现在我有一个带有特殊字符的字符串,例如 xed
或 xa0
.尝试导入它(通过 fromJSON(correctJSON(string))
(时,我得到 correctJSON
函数的错误:
Fehler in parseJSON(txt) : lexical error: invalid bytes in UTF8 string.
uch sind.Mutig von bd. Seiten�������������������������������
(right here) ------^
包含有问题字符的推文是 AFAICS:
[{"created_at":"Fri Feb 07 18:35:02 +0000 2014","id":431858659656990721,"id_str":"431858659656990721","text":"RT @FHubersr: @peteraltmaier //die Schwarz-Grünen werden zeigen, daß sich Ökologie und Ökonomie vertragen und kein Widerspruch sind.Mutig v…","source":"<a href=\"http://twitter.com/download/iphone\" rel=\"nofollow\">Twitter for iPhone</a>","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":378693834,"id_str":"378693834"},"geo":null,"coordinates":null,"place":null,"contributors":null,"retweeted_status":{"created_at":"Fri Feb 07 18:32:30 +0000 2014","id":431858022366064640,"id_str":"431858022366064640","text":"@peteraltmaier //die Schwarz-Grünen werden zeigen, daß sich Ökologie und Ökonomie vertragen und kein Widerspruch sind.Mutig von bd. Seitenxedxa0xbdxedxb1x8dxedxa0xbdxedxb8x8e","source":"<a href=\"http://twitter.com/download/iphone\" rel=\"nofollow\">Twitter for iPhone</a>","truncated":false,"in_reply_to_status_id":431845492579123201,"in_reply_to_status_id_str":"431845492579123201","in_reply_to_user_id":378693834,"in_reply_to_user_id_str":"378693834","in_reply_to_screen_name":"peteraltmaier","user":{"id":2172292811,"id_str":"2172292811"},"geo":null,"coordinates":null,"place":null,"contributors":null,"retweet_count":3,"favorite_count":4,"favorited":false,"retweeted":false,"lang":"de"},"retweet_count":3,"favorite_count":0,"favorited":false,"retweeted":false,"lang":"de"}]
我已经尝试了很多东西,但即使在这里阅读了一些线程,我也无法想出可以替换所有有问题的特殊字符的解决方案。
注意:有趣的是,当我想通过 fromJSON 导入单个推文时,我没有收到错误。但是一旦我导入正确的 JSON 字符串,它就会抛出错误。但是我需要正确的 JSON,因为出现了很多 次......
PS:我只粘贴了有问题的推文。在这里,您可以看到我的 API 调用的完整输出也包含以下内容:https://p.mehl.mx/?53c04753c247a48a#5w+HtSCYpcjRwSk0PdsP3P1w3u+Z22/f6GKMJRoW//8=
感谢您的帮助!
好的,我自己找到了一个可能的答案,它适用于我迄今为止收集的前 5000 条推文:
correctJSON <- function(string) {
string <- str_replace_all(string, pattern = "[^[:print:]]", replacement = " ")
string <- str_replace_all(string, pattern = perl('\\(?![tn"])'), replacement = " ")
return(string)
}
正则表达式[^[:print:]]
适用于特殊字符,如 xed
、 n
也可能 U....
.仅对于单个您将需要第二个(perl(正则表达式。
所以它现在有效,希望也适用于我将导入的许多即将到来的推文。如果发生意外情况,我会编辑。