我有一个字符串
x <- "Name of the Student? Michael Sneider"
我想从中提取“Michael Sneider”。
我用过:
str_extract_all(x,"[a-z]+")
str_extract_all(data,"\\?[a-z]+")
但无法提取名称。
答案 0 :(得分:3)
我认为这应该有帮助
substr(x, str_locate(x, "?")+1, nchar(x))
答案 1 :(得分:3)
试试这个:
sub('.*\\?(.*)','\\1',x)
答案 2 :(得分:2)
x <- "Name of the Student? Michael Sneider"
sub(pattern = ".+?\\?" , x , replacement = '' )
答案 3 :(得分:2)
为了利用问题的宽松措辞,我们可以过度使用自然语言处理从字符串中提取所有名称:
library(openNLP)
library(NLP)
# you'll also have to install the models with the next line, if you haven't already
# install.packages('openNLPmodels.en', repos = 'http://datacube.wu.ac.at/', type = 'source')
s <- as.String(x) # convert x to NLP package's String object
# make annotators
sent_token_annotator <- Maxent_Sent_Token_Annotator()
word_token_annotator <- Maxent_Word_Token_Annotator()
entity_annotator <- Maxent_Entity_Annotator()
# call sentence and word annotators
s_annotated <- annotate(s, list(sent_token_annotator, word_token_annotator))
# call entity annotator (which defaults to "person") and subset the string
s[entity_annotator(s, s_annotated)]
## Michael Sneider
过度破坏?大概。但有趣的是,实际上并没有那么难实现。
答案 4 :(得分:1)
str_match
在这种情况下更有帮助
str_match(x, ".*\\?\\s(.*)")[, 2]
#[1] "Michael Sneider"