Мне нужно удалить все слова (или заменить их пробелами) в строках, которые имеют не алфавитные символы (кроме дефисов и апострофов) в середине R. Может ли кто-нибудь помочь?Спасибо.
например,
str = "he@llo wor*ld i'm using state-of-the-art technologies it's i4u"
ожидаемый результат " i'm using state-of-the-art technologies it's "
Я пробовал следующее регулярное выражение.
lines <- c("i'm",
'gas-lighting',
"i'm gas-lighting",
"i-love-you",
"i@u",
"b2b",
"i'm gas-lighting u i@u b2b")
gsub("\\w+[^a-z'-]+\\w+", " ", lines)
[1] "i'm" "gas-lighting" "i' -lighting" "i-love-you" " "
" " "i' - "
Проблема в пробеле между словами?Пытался пропустить пробел.
gsub("\\w+[^a-z\\s'-]+\\w+", " ", lines)**
[1] "i'm" "gas-lighting" "i' -lighting" "i-love-you" " "
" " "i' - "
Это не пропустит пробелы?Ожидаются следующие строки.
[1] "i'm" "gas-lighting" "i'm gas-lighting" "i-love-you" " "
" " "i'm gas-lighting u "
Обновление 2: все в порядке, пока что все в порядке.
> lines <- c("i'm",
+ 'gas-lighting',
+ "i'm gas-lighting",
+ "i-love-you",
+ "i@u",
+ "b2b",
+ "i'm gas-lighting u and you and you i@u b2b",
+ " he@llo wor$ld how*are&you ")
>
> # split a string at spaces then remove the words
> # that contain any non-alphabetic characters (excpet "-", "'")
> # then paste them together (separate them with spaces)
> unlist(lapply(lines, function(line){
+ words <- unlist(strsplit(line, "\\s+"))
+ words <- words[!grepl("[^a-z'-]", words, perl=TRUE)]
+ paste(words, collapse=" ")}))
[1] "i'm" "gas-lighting"
[3] "i'm gas-lighting" "i-love-you"
[5] "" ""
[7] "i'm gas-lighting u and you and you" ""
Обновление 1: Пока я использую следующее регулярное выражение.
> # replace word at the beginning of a string
> lines <- gsub("^\\s*\\w*[^a-z'-]+\\w*", " ", lines); lines
[1] "i'm" "gas-lighting" "i'm gas-lighting" "i-love-you"
[5] " " " " "i'm gas-lighting u i@u "
> # replace word at the end of a string
> lines <- gsub("\\s[a-z]+[^a-z'-]+\\w*$", " ", lines); lines
[1] "i'm" "gas-lighting" "i'm gas-lighting" "i-love-you"
[5] " " " " "i'm gas-lighting u i@u "
> # replace words between spaces
> gsub("\\s\\w*[^a-z'-]+\\w*\\s", " ", lines)
[1] "i'm" "gas-lighting" "i'm gas-lighting" "i-love-you" " "
[6] " " "i'm gas-lighting u "