【问题标题】:Get a specific word and the following one in a string获取字符串中的特定单词和以下单词
【发布时间】:2017-03-28 08:05:34
【问题描述】:

我想在字符串中获取属名和种名。 示例:

"He saw a Panthera leo in the savanna"

我希望得到"Panthera leo" 并指定属名。

我尝试使用word 函数(包stringr):

my_sentence<-"He saw a Panthera leo in the savanna"
word(my_sentence,"Panthera",+1)

我知道问题出在“+1”参数上。你有什么线索吗?

也许我应该使用 gsub 函数?

【问题讨论】:

  • 就ind &lt;- grep('Panthera', strsplit(x, ' ')[[1]]); word(x, ind, ind+1) [1] "Panthera leo"

标签: r regex gsub stringr


【解决方案1】:
my_sentence<-"He saw a Panthera leo in the savanna"
x = strsplit(my_sentence, " ")
index = grep("Panthera", x, value=F)
want =x[c(index, index+1)][[1]]

【讨论】:

  • 几件事。 grep 的默认值已经是 FALSE(无需指定)。还有句子多的时候unlist(strsplit(...))会给出错误的结果
【解决方案2】:

正则表达式-Fu:

> m <- gregexpr('panthera\\W\\w\\w+', "He saw a Panthera leo in the 
savanna", ignore.case = T)
> regmatches("He saw a Panthera leo in the savanna", m)
[[1]]
[1] "Panthera leo"

\W\w\w+ 是一个非单词字符,一个单词字符,然后是一个或多个单词字符。这意味着 panthera 之后的任何内容都必须至少有 2 个字符。

在stringr 中看起来像这样:

> s <- "He saw a Panthera leo in the savanna"
> pat <- regex('panthera\\W\\w\\w+', ignore_case = T)
> str_extract(s, pat)
[1] "Panthera leo"

我想我更喜欢那个。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-17
    • 2018-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-02
    • 1970-01-01
    相关资源
    最近更新 更多