2015-08-08 66 views
-1

我使用R来清理存储在我的硬盘驱动器中的html文件,然后导出为txt文件。然而,在输出的文本文件中,我看到了很多奇怪的字符,例如< U + 0093>,< U + 0094> < U + 0093>等等。在我看来,引号或子弹点(或者其他一些)未正确解析/显示。我该如何解决这个问题?R HTML清理 - 如何摆脱输出中的奇怪字符?

这里是original HTML file

下面是我一直使用的代码:

library(bitops) 
library(RCurl) 
library(XML) 
rawHTML <- paste(readLines("2488-R20130221-C20121229-F22-0-1.htm"), collapse="\n") 
doc = htmlParse(rawHTML, asText=TRUE, encoding="UTF-8") 
plain.text <- xpathSApply(doc, "//text()[not(ancestor::script)][not(ancestor::style)][not(ancestor::noscript)][not(ancestor::form)]", xmlValue) 
write.table(plain.text, file="2488.txt", row.names=FALSE, col.names=FALSE, quote=FALSE) 

回答

0

如果你只需要文字,你一个做转换与iconv为ASCII。此外,您不需要使用write.table此为writeLines将很好地做到:

library(bitops) 
library(RCurl) 
library(XML) 

rawHTML <- paste(readLines("~/Dropbox/2488-R20130221-C20121229-F22-0-1.htm"), collapse="\n") 
doc <- htmlParse(rawHTML, asText=TRUE, encoding="UTF-8") 
plain.text <- xpathSApply(doc, "//text()[not(ancestor::script)][not(ancestor::style)][not(ancestor::noscript)][not(ancestor::form)]", xmlValue) 
writeLines(iconv(plain.text, to="ASCII"), "~/Dropbox/2488wl.txt") 

你也可以使用rvest(你还需要iconv):

library(xml2) 
library(rvest) 

pg <- html("~/Dropbox/2488-R20130221-C20121229-F22-0-1.htm") 

target <- "//text()[not(ancestor::script)][not(ancestor::style)][not(ancestor::noscript)][not(ancestor::form)]" 

pg %>% 
    html_nodes(xpath=target) %>% 
    html_text() %>% 
    iconv(to="ASCII") %>% 
    writeLines("~/Dropbox/2488rv.txt") 

您也可避免管道如果你想要:

converted <- iconv(html_text(html_nodes(pg, xpath=target)), to="ASCII") 
writeLines(converted, "~/Dropbox/2488rv.txt") 
+0

谢谢,我试过'='ASCII''但很多内容都丢失了,而只显示了几个“NA”。一旦我将其更改为UTF-8,结果证明它很好。你知道这是什么原因吗? – kxiang

+0

另外,有时线条之间会有相当多的空白,你是否知道如何摆脱它们(即,使输出更紧密)? – kxiang

+0

很高兴UTF-8工作(不知道你需要什么,虽然我很惊讶UTF-8确实工作)。 ASCII是最兼容的,但限制性更强。我会更新帖子的内容。 – hrbrmstr