【问题标题】:Extracting text from *.txt files in R从 R 中的 *.txt 文件中提取文本
【发布时间】:2019-05-06 04:05:19
【问题描述】:

我已使用 Mac 的 Expressions 来确认我的 Regex 是否有效,但我找不到从我的文本文件中提取信息的命令。我有 2,500 个文本文件,我需要提取每个文档的日期以填充数据集。仅供参考,“日期”是要提取的第一个变量,还会有其他变量。文件的格式各不相同,并且有多个日期。我只对每个文件的第一个日期感兴趣。一些文件的日期换行,另一些文件以“日期”或“日期”开头。

每个文本文档的示例:

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

显然这实际上不起作用!

非常感谢! 伊恩

【问题讨论】:

    标签: r regex text tm


    【解决方案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"
    

    【讨论】:

    • 谢谢,我输入了 \\ 但是这里加载的问题只有一个 \。
    【解决方案2】:

    我相信这样做。它使用内置变量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"
    

    【讨论】:

      【解决方案3】:

      谢谢大家,这是一种享受!

      库(字符串)

      txt = "Bangor Dorset LL56 43r\n 日期:2009 年 7 月 10 日 \n 请注意:blah blah blah 文本放在这里,内容很多。行动:"

      str_match(string = txt, pattern = "\d{1,2}\s+(?:一月|二月|三月|四月|五月|六月|七月|八月|九月|十月|十一月|十二月)\s+ \d{4}")

          [,1]          
      

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-29
        • 1970-01-01
        相关资源
        最近更新 更多