【问题标题】:Re-format scraped date in R在 R 中重新格式化抓取的日期
【发布时间】:2014-01-27 12:39:03
【问题描述】:

我已经抓取了 HTML,现在我有这样的行:

                               rows
1: for the Year Ended 31 March 2013

我只想提取表达式"31 March 2013"。表达式周围的文本可能会有所不同。表达式要转成日期格式,最好是31-3-2013

如何解决这个问题?

【问题讨论】:

  • 日期总是最后三个字吗?是否还有其他数字,或者您可以使用一个正则表达式来为您提供两个数字和介于两者之间的单词吗?
  • 问题是我还不知道,直到我对所有文件进行报废。但包括它不会是最后三个单词的可能性,会很棒。

标签: regex r date


【解决方案1】:

如果您的字符串中没有其他数字,您可以使用以下方法:

string <- "for the Year Ended 31 March 2013"

format(as.Date(sub(".*?(\\d+ \\w+ \\d+).*", "\\1", string), 
               "%d %B %Y"), "%d-%m-%Y")
# [1] "31-03-2013"

这里sub 提取相关子字符串,as.Date 创建一个表示Date 值的对象,format 更改日期元素的顺序。


它也适用于额外的文本和一位数的日子:

string <- c("for the Year Ended 31 March 2013",
            "1 January 2013 the Year Began",
            "for the Year Ended 31 March 2013 and not now")
format(as.Date(sub(".*?(\\d+ \\w+ \\d+).*", "\\1", string),
       "%d %b %Y"), "%d-%m-%Y")
# [1] "31-03-2013" "01-01-2013" "31-03-2013"

【讨论】:

    【解决方案2】:

    另一种选择:

    library(stringr)
    library(lubridate)
    dmy(str_extract(xx,'[0-9]{2}.*[0-9]{4}$'))
    [1] "2013-03-31 UTC"
    

    【讨论】:

      【解决方案3】:
      rows <- c("for the Year Ended 31 March 2013 ... 31 March 2013 ...",
                "for the Year Ended 1 December 2011")
      m <- gregexpr("[0-9]+ [A-z]+ [0-9]{4}", rows)
      # Sys.setlocale("LC_TIME", "english")
      (res <- lapply(regmatches(rows, m), as.Date, "%d %B %Y"))
      # [[1]]
      # [1] "2013-03-31" "2013-03-31"
      # 
      # [[2]]
      # [1] "2011-12-01"
      lapply(res, format.Date, "%d-%m-%Y") # or "%d-%e-%Y"
      # [[1]]
      # [1] "31-03-2013" "31-03-2013"
      # 
      # [[2]]
      # [1] "01-12-2011"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-07-31
        • 2021-10-30
        • 2021-09-14
        • 2012-06-22
        • 1970-01-01
        • 2019-12-25
        • 1970-01-01
        • 2021-04-06
        相关资源
        最近更新 更多