【问题标题】:Matching strings with str_detect and regex使用 str_detect 和 regex 匹配字符串
【发布时间】:2018-06-09 13:19:35
【问题描述】:

我有一个包含非结构化文本的数据框。在这个可重现的示例中,我直接从 SEC 网站下载 10K 公司文件,并使用 read.table 加载它。

dir = getwd(); setwd(dir)

download.file("https://www.sec.gov/Archives/edgar/data/2648/0000002648-96-000013.txt", file.path(dir,"filing.txt"))

filing <- read.table(file=file.path(dir, "filing.txt"), sep="\t", quote="", comment.char="")
droplevels.data.frame(filing)

我想删除 SEC 标题,以便专注于文档的主体(从第 216 行开始)并将我的文本划分为部分/项目。

> filing$V1[216:218]
[1] PART I 
[2] Item  1.    Business.                                                                                                                                                      
[3]            A.  Organization of Business                                      

因此,我尝试匹配以单词 Item(或 ITEM)开头的字符串,后跟一个或多个空格、一个或两个数字、一个点、一个或多个空格和一个或多个单词。例如:

Item 1. Business.
ITEM 1.  BUSINESS
Item  1.  Business
Item 10. Directors and Executive Officers of 
ITEM  10. DIRECTORS AND EXECUTIVE OFFICERS OF THE REGISTRANT

我的尝试涉及 str_detect 和正则表达式,以便创建一个变量计数,每次字符串匹配时都会跳转。

library(dplyr)
library(stringr)
tidy_filing <- filing %>% mutate(count = cumsum(str_detect(V1, regex("^Item [\\d]{1,2}\\.",ignore_case = TRUE)))) %>% ungroup()

但是,我缺少前 9 项,我的计数仅从第 10 项开始。

tidy_filing[c(217, 218,251:254),]
       V1                               count
217    Item  1.   Business.               0
218    A.  Organization of Business 3     0
251                          PART III     0
252    Item 10.   Directors etc.   38     1
253    Item 11.   Executive Compens. 38   2
254    Item 12.   Security Ownership. 38  3           

任何帮助将不胜感激。

【问题讨论】:

  • 双空格搞砸了 - 请改用"^Item\\s+[\\d]{1,2}\\."
  • @AndrewGustar 你应该添加这个作为答案。
  • @AndrewGustar,感谢您的帮助!如果您将其添加为答案,我会接受。

标签: r regex string stringr


【解决方案1】:

问题在于单个数字项目有两个空格,以便与两位数字项目对齐。您可以通过将正则表达式字符串更改为

来解决这个问题
"^Item\\s+\\d{1,2}\\."

【讨论】:

  • 请注意,在括号表达式中使用散弹手字符类是个坏主意(这是[...] 中的唯一模式)。此外,如果一个人想使用(g)sub 而没有使用perl=TRUE 使用"[\\d]" 会很惊讶没有匹配。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-26
  • 1970-01-01
  • 2014-11-18
  • 1970-01-01
  • 2014-08-05
  • 1970-01-01
  • 2019-03-14
相关资源
最近更新 更多