【问题标题】:Keep only the text of a label仅保留标签的文本
【发布时间】:2020-08-04 18:05:13
【问题描述】:

在具有格式标签的文本中,例如

data.frame(id = c(1, 2), text = c("something here <h1>my text</h1> also <h1>Keep it</h1>", "<h1>title</h1> another here"))

有人怎么能用逗号分隔选项只保留&lt;h1&gt; &lt;/h1&gt;中的文本:

data.frame(text = c("my text, Keep it", "title"), id = c(1, 2))

【问题讨论】:

    标签: r quanteda


    【解决方案1】:

    我们可以使用str_extract_all。使用正则表达式环视,获取标记后的字符,然后遍历list 输出和paste 提取的字符串

    library(stringr)
    data.frame(text = sapply(str_extract_all(df1$text, "(?<=<h1>)[^<]+"), 
          paste, collapse=", "), id = df1$id)
    #               text id
    #1 my text, Keep it  1
    #2            title  2
    

    【讨论】:

      【解决方案2】:

      你可以使用网页抓取技能。

      library(rvest)
      
      sapply(df$text, function(x) {
        read_html(x) %>% html_nodes(css = "h1") %>% html_text %>% toString
      }, USE.NAMES = F)
      
      # [1] "my text, Keep it"
      # [2] "title"
      

      【讨论】:

        【解决方案3】:

        如果您想为此使用 quanteda,您可以将其转换为语料库,然后通过两个 corpus_segment() 调用对其进行处理,一个用于获取之前的文本,第二个用于然后只需选择 .然后您可以使用texts(x, groups = docid()) 重新组合文本,指定spacer = ", "

        以下是您想要的输出:

        library("quanteda")
        ## Package version: 2.1.1
        
        df <- data.frame(
          id = c(1, 2),
          text = c("something here <h1>my text</h1> also <h1>Keep it</h1>", "<h1>title</h1> another here")
        )
        
        charvec <- corpus(df, docid_field = "id") %>%
          corpus_segment("</h1>", pattern_position = "after") %>%
          corpus_segment("<h1>", pattern_position = "before") %>%
          texts(groups = docid(.), spacer = ", ")
        

        然后将其转换为您想要的data.frame

        data.frame(text = charvec, id = names(charvec))
        ##               text id
        ## 1 my text, Keep it  1
        ## 2            title  2
        

        【讨论】:

          猜你喜欢
          • 2014-08-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-08-17
          相关资源
          最近更新 更多