【问题标题】:How do I extract dates from .rtf in R如何从 R 中的 .rtf 中提取日期
【发布时间】:2019-09-07 11:03:36
【问题描述】:

我有 .rtf 格式的文章,我想从中提取日期。文章长这样:

第一行是标题,后面是一个空行。然后它列出了以下内容,每个都在自己的行中:

  • 字数
  • 日期
  • 通讯社
  • 通讯社的缩写
  • 语言
  • 版权信息

我已经尝试了以下代码,但它似乎不起作用。似乎问题在于提取日期。

##First I read the file using this code: 
htmlText <- read_file(paste("/Users/adhyantarahma/Desktop/Factiva-20190905-0316.rtf"))

##then I removed new lines tags
removeNewLines <- gsub("\n"," ",htmlText) 

##and I changed " to ' in text
cleanLines <- gsub("\"", "'", removeNewLines) 

print(cleanLines)

##the relevant part of cleanLines look like this 
#\\ 347 words\\ 9 April 2016\\ FARS News Agency\\ FARSNA\\ English\\

##then I used this to extract date 
date <- str_extract_all(htmlText, "words \\d{1,2} [A-Z][a-z]+ \\d{4}")[[1]]

但它似乎没有选择日期。当我运行它时,它总是说没有字符。

我应该怎么做才能取到日期?

【问题讨论】:

    标签: r regex date


    【解决方案1】:

    我只是按照您的解决方案并将其转变为稍作修改的解决方案。

    library(readr)
    library(stringr)
    htmlText <- read_file("Factiva-20190905-0316.rtf")
    
    
    # -------------------------------------------------------------------------
                  # output -- htmlText
    # [1] "347 words\n9 April 2016\nFARS News Agency\nFARSNA\nEnglish\n"
    
    # -------------------------------------------------------------------------
    
    #replace "\n" with a space   
    removeNewLines <- gsub("\n"," ",htmlText) 
    
    # -------------------------------------------------------------------------
                # output -- removeNewLines
    # [1] "347 words 9 April 2016 FARS News Agency FARSNA English "
    
    # -------------------------------------------------------------------------
    
           # extract the date from removedNewLines
    my_date <- str_extract_all(removeNewLines, "\\d{1,2} [A-Z][a-z]+ \\d{4}")[[1]]
            # output -- my_date
    #[1] "9 April 2016"
    
    # -------------------------------------------------------------------------
    

    【讨论】:

      猜你喜欢
      • 2014-05-01
      • 2014-11-20
      • 1970-01-01
      • 2023-03-24
      • 2015-05-25
      • 1970-01-01
      • 2017-01-05
      • 1970-01-01
      相关资源
      最近更新 更多