我有一大堆HTML文件,其中包含来自节点span
中杂志的文本。我的PDF到HTML转换器在整个HTML中插入了字符实体
。问题是在R中,我使用xmlValue
函数(在XML包中)来提取文本,但只要有
,就会消除单词之间的空格。例如:
<span class="ft6">kids, and kids in your community, in DIY projects. </span>
将来自xmlValue
函数:
"kids,and kids in your community,in DIYprojects."
我认为解决此问题的最简单方法是在通过
运行span
个节点之前找到所有xmlValue
,并将其替换为" "
(空间)。我该怎么做?
答案 0 :(得分:1)
我重写了答案,以反映原始海报无法从XMLValue
获取文字的问题。可能有不同的方法来解决这个问题,但一种方法是直接打开/替换/编写HTML文件本身。通常使用正则表达式处理XML / HTML是一个坏主意,但在这种情况下,我们有一个直接的问题,即不需要的不间断空格,所以它可能不是太大的问题。以下代码是如何创建匹配文件列表并对内容执行gsub
的示例。根据需要修改或扩展应该很容易。
setwd("c:/test/")
# Create 'html' file to use with test
txt <- "<span class=ft6>kids, and kids in your community, in DIY projects. </span>
<span class=ft6>kids, and kids in your community, in DIY projects. </span>
<span class=ft6>kids, and kids in your community, in DIY projects. </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(" "," ", in.lines)
# Write out the corrected lines to a new file
writeLines(out.lines, paste("new_", x, sep = ""))
})