我有一个示例xml输入字符向量,如下所示。我不使用xml解析函数,因为xml文档不是完全有效的:
x1 <- readLines("test.xml)
x1
<important>
<hdtitle>Important:</hdtitle>
<stepgrp type="unordered-bullet">
<step>
Ensure the dark link is facing up.
</step>
<step>
If using the chain and sprockets again, align the darkened
link with the marked sprockets made during disassembly.
</step>
</stepgrp>
</important>
Install the drive chain to the drive sprocket and the driven
sprocket.
</step>我想要在</step>和连续的</step>之间找到</important>的位置,条件是:
1)在</step>的位置和连续的</step>之间不发生<step>
我想要的输出如下:
<important>
<hdtitle>Important:</hdtitle>
<stepgrp type="unordered-bullet">
<step>
Ensure the dark link is facing up.
</step>
<step>
If using the chain and sprockets again, align the darkened
link with the marked sprockets made during disassembly.
</step>
</stepgrp>
</important><step>
Install the drive chain to the drive sprocket and the driven
sprocket.
</step>如果满足上述条件,我将在</important>之后添加<step>。
发布于 2015-08-19 00:49:15
imp_end <- grep("<\\/important>", x)
step_start <- grep("<step>", x)
step_end <- grep("<\\/step>", x)
imp_intervals <- cut(imp_end, step_end)
step_start_intervals <- na.omit(cut(step_start, step_end))
valid <- na.omit(imp_intervals[!imp_intervals %in% step_start_intervals])
indx <- na.omit(imp_end[imp_intervals == valid])
x[indx] <- gsub("^(<\\/important>)$", "\\1<step>", x[indx])
x
# [1] "<important>"
# [2] "<hdtitle>Important:</hdtitle>"
# [3] "<stepgrp type=\"unordered-bullet\">"
# [4] "<step>"
# [5] "Ensure the dark link is facing up."
# [6] "</step>"
# [7] "<step>"
# [8] "If using the chain and sprockets again, align the darkened"
# [9] "link with the marked sprockets made during disassembly."
# [10] "</step>"
# [11] "</stepgrp>"
# [12] "</important><step>"
# [13] "Install the drive chain to the drive sprocket and the driven"
# [14] "sprocket."
# [15] "</step>" 我使用cut为这些线创建间隔。我假设数据是垂直的,如示例中所示。然后使用valid,我查找在同一时间间隔内位于"</step>"和没有"<step>"字符串之间的</important>的位置。我试着破译你的规则逻辑,让我知道它是否是你要找的。
Data
df <- read.table(text='
<important>
<hdtitle>Important:</hdtitle>
<stepgrp type="unordered-bullet">
<step>
Ensure the dark link is facing up.
</step>
<step>
If using the chain and sprockets again, align the darkened
link with the marked sprockets made during disassembly.
</step>
</stepgrp>
</important>
Install the drive chain to the drive sprocket and the driven
sprocket.
</step>', sep="\n", stringsAsFactors=F)
x <- df$V1https://stackoverflow.com/questions/32076890
复制相似问题