我正在尝试从 PGN 国际象棋符号中删除时钟时间。例如,如果我有字符串:
“1.e4 {[%clk 0:00:59.5]} 1...b6 {[%clk 0:00:57.4]} 2.NC3 {[%clk 0:00:59.4]} 2... Bb7 {[%clk 0:00:57.2]}"
我怎样才能得到 59.5、57.4 等?
我是 R 初学者,我尝试了 strsplit() 但没有成功
这是使用 stringr 包的方法:
library(stringr)
t <- "1. e4 {[%clk 0:00:59.5]} 1... b6 {[%clk 0:00:57.4]} 2. Nc3 {[%clk 0:00:59.4]} 2... Bb7 {[%clk 0:00:57.2]}"
result <- str_extract_all(t, "\\d:\\d\\d:\\d\\d.\\d", simplify = TRUE) %>% gsub("\\d:\\d\\d:", "", .)
result
[,1] [,2] [,3] [,4]
[1,] "59.5" "57.4" "59.4" "57.2"
假设您想要完整的时间为
numeric
,我们需要首先使用类似的内容提取时间字符串
st2 <- regmatches(st, gregexpr("(?<=clk )[0-9:.]+", st, perl = TRUE))
st2
# [[1]]
# [1] "0:00:59.5" "0:00:57.4" "0:00:59.4" "0:00:57.2"
然后我们可以使用辅助函数将其转换为“秒”:
time2num <- function(x) {
vapply(strsplit(x, ':'), function(y) sum(as.numeric(y) * 60^((length(y)-1):0)),
numeric(1), USE.NAMES=FALSE)
}
time2num(unlist(st2))
# [1] 59.5 57.4 59.4 57.2