当我尝试在R中获取数字部分时出现问题。例如,原始字符串为"buy 1000 shares of Google at 1100 GBP"
我需要分别提取份额(1000
)和价格(1100
)。此外,我需要提取股票的数量,该数量始终显示在"shares of"
之后。
我知道sub
和gsub
可以替换字符串,但我应该使用哪些命令来提取字符串的一部分?
答案 0 :(得分:2)
1)按顺序提取所有数字:
s <- "buy 1000 shares of Google at 1100 GBP"
library(gsubfn)
strapplyc(s, "[0-9.]+", simplify = as.numeric)
,并提供:
[1] 1000 1100
2)如果这些数字可以是任何顺序,但如果共享的数量总是后跟单词&#34; shares&#34;然后价格总是跟着英镑:
strapplyc(s, "(\\d+) shares", simplify = as.numeric) # 1000
strapplyc(s, "([0-9.]+) GBP", simplify = as.numeric) # 1100
返回字符串中与parens中正则表达式部分匹配的部分。
3)如果知道该字符串的格式为:Z GBP的X股,那么可以像这样提取X,Y和Z:
strapplyc(s, "(\\d+) shares of (.+) at ([0-9.]+) GBP", simplify = c)
ADDED 修改后的模式,允许使用数字或点。还添加了(3)以上和以下内容:
strapply(c(s, s), "[0-9.]+", as.numeric)
strapply(c(s, s), "[0-9.]+", as.numeric, simplify = rbind) # if ea has same no of matches
strapply(c(s, s), "(\\d+) shares", as.numeric, simplify = c)
strapply(c(s, s), "([0-9.]+) GBP", as.numeric, simplify = c)
strapplyc(c(s, s), "(\\d+) shares of (.+) at ([0-9.]+) GBP")
strapplyc(c(s, s), "(\\d+) shares of (.+) at ([0-9.]+) GBP", simplify = rbind)
答案 1 :(得分:1)
您可以使用sub
功能:
s <- "buy 1000 shares of Google at 1100 GBP"
# the number of shares
sub(".* (\\d+) shares.*", "\\1", s)
# [1] "1000"
# the stock
sub(".*shares of (\\w+) .*", "\\1", s)
# [1] "Google"
# the price
sub(".* at (\\d+) .*", "\\1", s)
# [1] "1100"
您还可以使用gregexpr
和regmatches
一次性提取所有子字符串:
regmatches(s, gregexpr("\\d+(?= shares)|(?<=shares of )\\w+|(?<= at )\\d+",
s, perl = TRUE))
# [[1]]
# [1] "1000" "Google" "1100"
答案 2 :(得分:0)
我觉得有必要加入强制性的stringr
解决方案。
library(stringr)
s <- "buy 1000 shares of Google at 1100 GBP"
str_match(s, "([0-9]+) shares")[2]
[1] "1000"
str_match(s, "([0-9]+) GBP")[2]
[1] "1100"
答案 3 :(得分:0)
如果要从文本中提取所有数字,请使用stringi
包中的此功能。
“Nd”是十进制数字的类。
stri_extract_all_charclass(c(123,43,"66ala123","kot"),"\\p{Nd}")
[[1]]
[1] "123"
[[2]]
[1] "43"
[[3]]
[1] "66" "123"
[[4]]
[1] NA
请注意,此处分别提取66和123个数字。