R中的HTML字符实体替换

时间:2013-01-15 00:13:52

标签: html r xml-parsing character replace

我有一大堆HTML文件,其中包含来自节点span中杂志的文本。我的PDF到HTML转换器在整个HTML中插入了字符实体 。问题是在R中,我使用xmlValue函数(在XML包中)来提取文本,但只要有 ,就会消除单词之间的空格。例如:

<span class="ft6">kids,&nbsp;and kids in your community,&nbsp;in                                   DIY&nbsp;projects.&nbsp;</span>

将来自xmlValue函数:

"kids,and kids in your community,in DIYprojects."

我认为解决此问题的最简单方法是在通过&nbsp;运行span个节点之前找到所有xmlValue,并将其替换为" "(空间)。我该怎么做?

1 个答案:

答案 0 :(得分:1)

我重写了答案,以反映原始海报无法从XMLValue获取文字的问题。可能有不同的方法来解决这个问题,但一种方法是直接打开/替换/编写HTML文件本身。通常使用正则表达式处理XML / HTML是一个坏主意,但在这种情况下,我们有一个直接的问题,即不需要的不间断空格,所以它可能不是太大的问题。以下代码是如何创建匹配文件列表并对内容执行gsub的示例。根据需要修改或扩展应该很容易。

setwd("c:/test/")
# Create 'html' file to use with test
txt <- "<span class=ft6>kids,&nbsp;and kids in your community,&nbsp;in                                   DIY&nbsp;projects.&nbsp;</span>
<span class=ft6>kids,&nbsp;and kids in your community,&nbsp;in                                   DIY&nbsp;projects.&nbsp;</span>
<span class=ft6>kids,&nbsp;and kids in your community,&nbsp;in                                   DIY&nbsp;projects.&nbsp;</span>"
writeLines(txt, "file1.html")

# Now read files - in this case only one
html.files <- list.files(pattern = ".html")
html.files

# Loop through the list of files
retval <- lapply(html.files, function(x) {
          in.lines <- readLines(x, n = -1)
          # Replace non-breaking space with space
          out.lines <- gsub("&nbsp;"," ", in.lines)
          # Write out the corrected lines to a new file
          writeLines(out.lines, paste("new_", x, sep = ""))
})