【发布时间】:2018-09-07 18:02:10
【问题描述】:
我有一个数据集,其中列是调查问题,行中的值包含响应者选择的答案以及多个 HTML 标记。我正在尝试删除所有 HTML 标签,只留下答案文本。
在 Excel 中,这可以通过使用空字符串作为替换来完成<*>。我无法弄清楚如何在 R 中执行此操作,因为我遇到的问题是我无法让通配符在第一个大于括号之后停止。相反,它只是将其识别为通配符的一部分并继续到字符串的末尾。我在下面包含了一个玩具数据集和我的尝试。
temp <- data.frame(one = c('<b style="font-weight: normal;"><span style="font-size: 12pt; font-family: "Times New Roman";white-space: pre-wrap;">Answer 1</span></b>',
'<b style="font-weight: normal;"><span style="font-size: 12pt; font-family: "Times New Roman";white-space: pre-wrap;">Answer 2</span></b>',
'<b style="font-weight: normal;"><span style="font-size: 12pt; font-family: "Times New Roman";white-space: pre-wrap;">Answer 3</span></b>'),
two = c('<b style="font-weight: normal;"><span style="font-size: 12pt; font-family: "Times New Roman";white-space: pre-wrap;">apples are red</span></b>',
'<b style="font-weight: normal;"><span style="font-size: 12pt; font-family: "Times New Roman";white-space: pre-wrap;">apples are blue</span></b>',
'<b style="font-weight: normal;"><span style="font-size: 12pt; font-family: "Times New Roman";white-space: pre-wrap;">apples are bananas</span></b>'))
temp[] <- sapply(temp, function(x) gsub('<.*>+', "", x))
# what I want the new temp to look like (above code results in empty strings
data.frame(one = c("Answer 1",
"Answer 2",
"Answer 3"),
two = c("apples are red",
"apples are blue",
"apples are bananas
我尝试使用第 n 次出现的代码和其他一些代码,但它仍然在第一个实例之后继续到字符串的末尾。
我缺少什么使其在第一个实例后终止的正则表达式命令?另外,我假设它会在完成第一次删除后移动到下一行,从而迫使我运行gsub() n 次,其中 n 是任何给定列中的最大标签数。这不是特别成问题,但有解决方法吗?
【问题讨论】: