簡體   English   中英

如何從(相對)非結構化文本中提取日期 [R]

[英]How to extract date from (relatively) unstructured text [R]

我很難從字符串中提取日期。 該字符串可以是以下幾種方式之一,但始終包括以下某種形式:

<full month name> <numeric date>, <year>

如:

DECEMBER 4, 2011

但是,字符串開頭的文本范圍很廣,采用以下所有形式:

THE PUBLIC SCHEDULE FOR MAYOR RAHM EMANUEL JUNE 9, 2011
THE PUBLIC SCHEDULE FOR MAYOR RAHM EMANUEL FOR OCTOBER 29 & OCTOBER 30, 2011
The Public Schedule for Mayor Rahm Emanuel December 17, 2011 through January 2, 2012
The Public Schedule for Mayor Rahm Emanuel December 8th and 9th, 2012
The Public Schedule for Mayor Rahm Emanuel – March 13, 2013

這些變化真的讓我失望。 通常,我會去掉字符串的前 X 個字符,並使用余數作為我的日期,但由於格式不斷變化,這是不可能的。 我一直在嘗試這種變化,但最終我創建的日期也有很多問題。

似乎grep()可能是這里使用的函數,但我真的不明白如何創建一個模式來捕獲這些日期,或者如何使用它的輸出。

感謝您的任何幫助!

這或多或少只是一種啟發式方法。 如果您刪除本月之前的所有內容,我們將獲得更易於管理的內容。 讓我們假設您的示例行在變量b

months.regex <- paste(month.name, collapse='|')
d <- gsub(paste0(".*(", months.regex, ")"), "\\1", 
          b[grep(months.regex, b, TRUE)], TRUE)

這僅選擇一個月的行並刪除該月之前的所有內容:

> d
[1] "JUNE 9, 2011"               "OCTOBER 30, 2011"          
[3] "January 2, 2012"            "December 8th and 9th, 2012"
[5] "March 13, 2013"            

月份和年份很容易提取:

month <- match(tolower(gsub("\\s.*", "", d)), tolower(month.name))
day <- gsub("\\S+\\s+(.*),.*", "\\1", d)
year <- as.integer(gsub(".*,\\s*(\\d{4})", "\\1", d))

真正的問題是自由格式的日期和多個日期。 沒有完美的方法 - 如果排隊時間超過一個月,上述方法將始終選擇最后一個日期。 為了減少多天,你可以使用類似的東西

day <- as.integer(gsub("\\D.*", "", day))

如果有多個,它將​​選擇第一天。 完整的結果是:

> paste(month.name[month], day, year)
[1] "June 9 2011"     "October 30 2011" "January 2 2012"  "December 8 2012"
[5] "March 13 2013"  

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM