所以我有一个字符串:
"我是健康组织的牙医。"
我想提取包含三个以上字母的第一个单词并将其放入数据表中的新列中,即在这种情况下"牙医"。我想我必须使用strsplit,但我不知道如何继续。
感谢任何帮助
此致 安特耶
答案 0 :(得分:2)
尝试这个简单的解决方案:
string<-"I am a dentist in a health organization."
words<-unlist(strsplit(string," "))
words[which.max(nchar(words)>3)]
[1] "dentist"
将此解决方案应用于添加列的数据框:
df<-data.frame(string=c("I am a dentist in a health organization.","a dentist in a health organization.","health organization."))
f<-function(string,n)
{
words<-unlist(strsplit(string," "))
return(words[which.max(nchar(words)>n)])
}
df$word<-unlist(lapply(as.character(df$string),f,n=3))
df
string word
1 I am a dentist in a health organization. dentist
2 a dentist in a health organization. dentist
3 health organization. health
答案 1 :(得分:1)
从头开始,"^"
,最短的字符序列".*?"
,后跟4个或更多字符的单词,"\\b(\\w{4,}\\b"
后跟剩余的文字{{{ 1}},并将所有内容替换为第一个(也是唯一一个)捕获组(即使用括号匹配正则表达式的部分)。
".*"
,并提供:
# input data frame
DF <- data.frame(x = c("I am a dentist in a health organization.",
"I am a dentist in a health organization."))
pat <- "^.*?\\b(\\w{4,})\\b.*"
transform(DF, longword = sub(pat, "\\1", x))
答案 2 :(得分:1)
\w{4,}
匹配任何单词字符(等于[a-zA-Z0-9 _]){4,}
量词 - 匹配4次和无限次,尽可能多次,根据需要回馈(贪婪)(?:\\w+)?
?
量词 - 匹配0到1次,尽可能多次,根据需要回馈(贪婪)+
量词 - 在一次和无限次之间匹配,尽可能多次,根据需要回馈(贪婪) strng <- "I am a dentist in a health organization."
stringr::str_extract(strng,"\\w{4,}(?:\\w+)?")
结果
[1] "dentist"