【问题标题】:HTML character entity replacement in RR中的HTML字符实体替换
【发布时间】:2012-12-29 01:03:42
【问题描述】:

我有大量 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."

我在想解决这个问题的最简单方法是在通过xmlValue 运行span 节点之前找到所有&amp;nbsp;,并将它们替换为" "(空格)。我将如何处理?

【问题讨论】:

标签: html r xml-parsing character replace


【解决方案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 = ""))
})

【讨论】:

  • 这是&amp;nbsp; 不是$nbsp,所以gsub("&amp;nbsp;"," ",test) 应该可以工作。
  • @thelatemail 感谢您发现这一点 - 拼写错误现已修复。必须避免在正确醒来之前发帖...
  • 我已经尝试过 gsub。问题是 xmlValue 的输入不是字符向量,而是“XMLinternalNode”。 gsub 需要可转换为字符向量或字符向量的东西,两者都不正确。
猜你喜欢
  • 2023-03-11
  • 2012-06-14
  • 2019-03-20
  • 2018-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多