我正在尝试使用R从文本中提取数字和日期。假设我有一个文本字符串向量V.text。文本字符串是包含数字和日期的句子。例如:
"listed on 2/14/2015 for 150000 and sold for $160,000 on 3/1/2015"
我想提取数字、金额和日期作为单独的向量分量。因此,输出将是两个向量:
1 1500000 160000
2 2/14/2015 3/1/2015
我尝试使用scan()
,但是没有得到想要的结果。如果有任何帮助,我将不胜感激。
发布于 2015-04-06 06:55:02
这样如何:
txt <- "listed on 2/14/2015 for 150000 and sold for $160,000 on 3/1/2015"
lapply(c('[0-9,]{5,}',
'[0-9]{1,2}/[0-9]{1,2}/[0-9]{4}'),
function(re) {
matches <- gregexpr(re, txt)
gsub(',', '', regmatches(txt, matches)[[1]])
})
## [[1]]
## [1] "150000" "160000"
## [[2]]
## [1] "2/14/2015" "3/1/2015"
(数字的第一个匹配项假定为5位或更多。如果小于,则这个更简单的正则表达式将与日期的年份冲突。)
发布于 2015-04-06 06:58:51
首先拆分出“单词”。带斜杠的是日期,只有$、数字或逗号的是数字。在后一种情况下,去掉非数字字符并将其转换为数字:
s <- strsplit(x, " ")[[1]]
grep("/", s, value = TRUE) # dates
## [1] "2/14/2015" "3/1/2015"
as.numeric(gsub("\\D", "", grep("^[$0-9,]+$", s, value = TRUE)))
## [1] 150000 160000
如果负数或十进制数是可能的,则将最后一行代码更改为:
as.numeric(gsub("[^-0-9.]", "", grep("^-?[$0-9,.]+$", s, value = TRUE)))
发布于 2015-04-06 06:58:30
快速脏方法:
x<-"listed on 2/14/2015 for 150000 and sold for $160,000 on 3/1/2015"
mydate<-regmatches(x,gregexpr("\\d{1,2}/\\d{1,2}/\\d{4}",x,perl=TRUE))
mynumber<-regmatches(sub(",","",x),gregexpr("\\d{6}",sub(",","",x),perl=TRUE))
您可以在r-fiddle中运行上面的代码
https://stackoverflow.com/questions/29462971
复制相似问题