【问题标题】:Extract specified number of words after a string in R在R中的字符串之后提取指定数量的单词
【发布时间】:2020-08-13 02:08:47
【问题描述】:

在下面的示例中,我正在尝试提取字符串“source:”之后的 4 个单词。

library(stringr)

x <- data.frame(end = c("source: from animal origin as Vitamin A / all-trans-Retinol: Fish in general, liver and dairy products;", "source: Eggs, liver, certain fish species such as sardines, certain mushroom species such as shiitake", "source: Leafy green vegetables such as spinach; egg yolks; liver"))


x$source = str_extract(x$end, '[^source: ](.)*')
 

当我尝试上面的代码时,我可以将“source:”之后的所有文本提取到一个新列中。我想知道是否有一种方法可以使用 stringr 或任何其他包仅提取“source”之后的前 4 个单词。

【问题讨论】:

    标签: r stringr text-extraction


    【解决方案1】:

    你可以使用:

    trimws(stringr::str_extract(x$end, '(?<=source:\\s)(\\w+,?\\s){4}'))
    #[1] "from animal origin as"       "Eggs, liver, certain fish"   
    #    "Leafy green vegetables such"
    

    ?&lt;= 是正向向后搜索'source:',后跟空格。

    我们在其后捕获 4 个“单词”,包括可选的逗号和空格。

    【讨论】:

    • 谢谢,我不知道trimws可以用于那个目的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多