【问题标题】:extract first brackets in text with a condition on some of the observations提取文本中的第一个括号,其中包含一些观察的条件
【发布时间】:2020-04-28 12:14:09
【问题描述】:

我有一些看起来像这样的数据:

# A tibble: 5 x 3
  grp   LP                                                      RE                                           
  <chr> <chr>                                                   <chr>                                        
1 4999  " PLATTEVILLE, Colo., Dec. 30, 2011 /PRNewswire/ -- Sy… " usa : United States | usco : Colorado | us…
2 9122  " 14:22 ET - Facebook (FB) has hired Campbell Brown, a… " usa : United States | namz : North America…
3 161   " DALLAS (Dow Jones)--Pioneer National Resources Co. (… " usa : United States | ustx : Texas | namz …

我正在尝试从LP 列中的文本中提取一些信息。

我想提取以下内容:

row1 = (NYSE Amex: SYRG) 第 2 行 = (FB) 第 3 行 = (PXD) 第 4 行 = … 第 5 行 = …

提取的“规则”是这样的。

在第 1 行和第 3 行中,我想在第一个双精度 -- 之后提取第一个括号 ()。 在第 2 行中,我只想提取第一个 ()。 在第 4 行和第 5 行 - 忽略。

数据:

structure(list(grp = c("4999", "9122", "161", "6047", "9585"), 
    LP = c(" PLATTEVILLE, Colo., Dec. 30, 2011 /PRNewswire/ -- Synergy Resources Corporation (NYSE Amex: SYRG) (\"Synergy Resources\"), a domestic oil and gas exploration and production company focused in the Denver-Julesburg Basin (\"D-J Basin\"), announced today that the underwriters have closed on their purchase of an additional 1,909,090 shares of Synergy Resources common stock at a public offering price of $2.75 per share. The shares were sold to underwriters to cover over-allotments in connection with the previously announced public offering of 12,727,273 shares of Synergy Resources' common stock that closed on December 21, 2011. The underwriters had previously notified Synergy Resources that they were exercising their over-allotment option in full. Synergy Resources expects net proceeds from the exercise of the over-allotment option to be approximately $4,900,000. Synergy Resources intends to use the net proceeds from the offering for its development drilling program in the Wattenberg Field.\n    ", 
    " 14:22 ET - Facebook (FB) has hired Campbell Brown, a former anchor for CNN and NBC, to run news partnerships. Brown will pitch and solicit publishers' feedback on products like Instant Articles and Facebook Live, but she won't decide how FB should handle sensitive and newsworthy content, like the 30-minute live video posted this week showing a Chicago man being tortured. FB has a wary relationship with media outlets. FB's dominance in digital ads has hurt the economics of many publishers. Users and media outlets have also criticized FB for allowing the spread of fake news on its platform in recent months. (deepa.seetharaman@wsj.com; @dseetharaman)\n    ", 
    " DALLAS (Dow Jones)--Pioneer National Resources Co. (PXD) sold 20.5 million barrels of oil equivalent reserves, or 2% of its total reserves, for total proceeds of $593 million.  \n\nPioneer also said it expects to report fourth-quarter earnings of 66 cents to 69 cents a share after having produced 198,000 barrels of oil equivalent per day during the quarter.  \n    ", 
    " \n \nTOP STORIES \n \nUS HOUSING, MANUFACTURING SHOW STRENGTH AT YEAR END \n   \n\nTwo sore spots in the U.S. economy show some strength at the end of 2006, with demand rising for expensive manufactured goods and new homes. New-home sales rise 4.8% in December to 1.120 million, but demand for whole year takes its biggest tumble since 1990, sliding 17% to 1.061 million. Separately, orders for durables advance by 3.1% last month to $221.87 billion.  \n    ", 
    " DuPont Co., looking to wrap up its merger with Dow Chemical Co., said its sales rose as the science company benefited from a change in the timing of seed deliveries.\n\nThe Delaware-based company also gave a downbeat outlook for the current quarter, projecting adjusted earnings of about $1.26 a share, below the Thomson Reuters consensus of $1.31 a share. As reported, DuPontexpects earnings to fall about 5% due to merger related expenses.\n    "
    ), RE = c(" usa : United States | usco : Colorado | usw : Western U.S. | namz : North America    ", 
    " usa : United States | namz : North America    ", " usa : United States | ustx : Texas | namz : North America | uss : Southern U.S.    ", 
    " usa : United States | namz : North America    ", " usde : Delaware | namz : North America | usa : United States | uss : Southern U.S.    "
    )), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, 
-5L))

【问题讨论】:

    标签: r


    【解决方案1】:

    我们可以使用str_match

    str_match(df$LP, '--?.*?(\\(.*?\\))')[, 2]
    #[1] "(NYSE Amex: SYRG)" "(FB)"  "(PXD)"  NA    NA 
    

    这将捕获圆括号中的所有内容,前面是可选的 '--'

    【讨论】:

      【解决方案2】:

      这样的事情怎么样,如果行有'--'然后查找'--'之后的第一个括号,否则查找第一个括号

      lapply(dat$LP, 
             function(x){
                 # split the text where there is --
                 x_0 <- (x %>% strsplit('--'))[[1]]
                 # if the text contains the string '--' 
                 # then length(x_0) is more than 1
                 if(length(x_0) > 1){
                     # remove the first part of the split, paste the rest back together
                     # meaning: start looking for the brackets after '--'
                     x <- paste(x_0[-1], collapse = ' ')
                 } # else we'll look for the brackets in the full string
                 # find where there's brackets in the text
                 pos <- gregexpr("\\(.*?\\)", x)[[1]]
                 # get the position of the first occurence
                 start <- pos[1]
                 # get the length of the first occurence
                 leng <- attr(pos, "match.length")[1]
                 # extract the string
                 res <- substr(x, start, start+leng)
                 return(res)
             })
      

      【讨论】:

        【解决方案3】:

        我们可以使用stri_extract_firststr_remove

        library(stringr)
        library(stringi)
        str_remove(stri_extract_first(df1$LP, regex = "--?[^(]+\\([^\\)]+\\)"), 
                        "^[^\\(]+")
        #[1] "(NYSE Amex: SYRG)" "(FB)"              "(PXD)"             NA                  NA  
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-05-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多