从R

时间:2018-12-04 16:51:38

标签: r regex text tm

我已经使用Mac表达式来确认我的Regex正常工作,但是找不到从文本文件中提取信息的命令。我有2500个文本文件,我需要提取每个文档的日期才能填充数据集。仅供参考,“日期”是要提取的第一个变量,还会有其他变量。文件的格式各不相同,并且有多个日期。我只对每个文档的首次约会感兴趣。有些文档的日期带有新行,而另一些文档则以“日期”或“日期”开头。

每个文本文档的示例:

Bangor
dorset
LL56 43r

date:         10 july 2009
take notice:  the blah blah blah text goes here and there's lots of it.
action:

有效的正则表达式:

"\\d{1,2}\\s+(?:january|february|march|april|may|june|july|august|september|october|november|december)\\s+\\d{4}"

文本文档在R Studio环境中作为单个元素字符向量可见。我想按原样提取文本,所以类似...

> strapply(NoFN, ("\\d{1,2}\\.?:january|february|march|april|may|june|july|august|september|october|november|december\\.\\d{4}")[[1]]
> [1] 10 july 2009

显然这实际上不起作用!

非常感谢! 伊恩

3 个答案:

答案 0 :(得分:1)

您的正则表达式不适合R,因为您需要转义\字符。

正则表达式应为:

"\\d{1,2}\\s+(?:january|february|march|april|may|june|july|august|september|october|november|december)\\s+\\d{4}"

如果您使用stringr包,并且您的文本已加载到txt,则可以执行以下操作:

library(stringr)

txt = "Bangor dorset LL56 43r\n date: 10 july 2009 \n take notice: the blah blah blah text goes here and there's lots of it. action:"

str_match(string = txt, pattern = "\\d{1,2}\\s+(?:january|february|march|april|may|june|july|august|september|october|november|december)\\s+\\d{4}")

        [,1]          
[1,] "10 july 2009"

答案 1 :(得分:0)

我相信这样做。它使用内置变量month.name,与问题不同,它使用()对月份进行分组。

txt <- "\n date: 10 july 2009 \n take notice: the blah blah blah text goes here and there's lots of it. action:"

pattern <- paste(tolower(month.name), collapse = "|")
pattern <- paste0("(", pattern, ")")
pattern <- paste("[[:digit:]]{1,2}[[:space:]]*", pattern, "[[:digit:]]{4}")

m <- regexpr(pattern, txt)
regmatches(txt, m)
#[1] "10 july 2009"

答案 2 :(得分:0)

谢谢大家,这很有效!

库(字符串)

txt =“班戈(Bangor)多塞特LL56 43r \ n日期:2009年7月10日\ n注意:等等等等文本在这里,并且有很多内容。动作:”

str_match(字符串= txt,模式=“ \ d {1,2} \ s +(?: 1月| 2月| 3月| 4月| 5月| 6月| 7月| 8月| 9月| 10月| 11月| 12月)\ s + \ d {4}“)

    [,1]          

[1,]“ 2009年7月10日”