在文本分析中,我们可能想从单个字符串或字符串向量中提取字符。可能需要使用此提取来创建一个新的字符串,其中包含一些需要进一步分析的特定单词。我们可以借助stringr包的str_sub函数来做到这一点。
请看以下字符串-
> x1<-"Removing harmful things from the road is an act of charity"
加载纵梁包-
> library(stringr) > str_sub(x1,1,8) [1] "Removing" > str_sub(x1,1,23) [1] "Removing harmful things" > str_sub(x1,29,37) [1] " the road" > str_sub(x1,30,37) [1] "the road" > str_sub(x1,-58,-51) [1] "Removing" > str_sub(x1,-58,-1) [1] "Removing harmful things from the road is an act of charity" > str_sub(x1,-7,-1) [1] "charity" > str_sub(x1,-14,-1) [1] "act of charity" > str_sub(x1,-17,-1) [1] "an act of charity"
让我们看一下字符串向量的字符数提取-
> x1<-c("Removing", "harmful", "things", "from", "the", "road", "is", "an", "act", "of", "charity") > str_sub(x1,1,2) [1] "Re" "ha" "th" "fr" "th" "ro" "is" "an" "ac" "of" "ch" > str_sub(x1,1,3) [1] "Rem" "har" "thi" "fro" "the" "roa" "is" "an" "act" "of" "cha" > str_sub(x1,1,10) [1] "Removing" "harmful" "things" "from" "the" "road" [7] "is" "an" "act" "of" "charity" > str_sub(x1,-7,-2) [1] "emovin" "harmfu" "thing" "fro" "th" "roa" "i" "a" [9] "ac" "o" "charit" > str_sub(x1,-7,-1) [1] "emoving" "harmful" "things" "from" "the" "road" "is" [8] "an" "act" "of" "charity" > str_sub(x1,-10,-1) [1] "Removing" "harmful" "things" "from" "the" "road" [7] "is" "an" "act" "of" "charity"