簡體   English   中英

刪除 R 中除反斜杠以外的所有標點符號

[英]Remove all punctuation except backslash in R

我正在嘗試從數據集中提取 html 鏈接。 我正在使用 strsplit 然后使用 grep 查找帶有鏈接的子字符串,但結果在字符串的開頭或結尾都有不需要的字符....我如何僅提取具有所需模式的字符串或保留字符串想要的模式

他就是我目前正在做的事情。

1)我使用strplit和“”(空格)作為分隔符分割了一大塊文本

2)接下來我grep strsplit的結果來找到模式

例如 grep("https:\\/\\/support.google.com\\/blogger\\/topic\\/[0-9]",r)

3)結果的一些變化如下所示......

https://support.google.com/blogger/topic/12457 
https://support.google.com/blogger/topic/12457.
[https://support.google.com/blogger/topic/12457]  
<<https://support.google.com/blogger/topic/12457>>
https://support.google.com/blogger/topic/12457,
https://support.google.com/blogger/topic/12457),
xxxxxxhttps://support.google.com/blogger/topic/12457),hhhththta
etc...

我如何只提取“ https://support.google.com/blogger/topic/12457 ”或在提取臟數據后如何刪除不需要的標點符號

提前謝謝。

qdapRegex包有一個很棒的函數,叫做rm_url ,非常適合這個例子。

install.packages('qdapRegex')
library(qdapRegex)

urls <- YOUR_VECTOR_OF_URLS
rm_url(urls, extract = T)

如果數據在某個時候是 HTML,你可以試試這個:

library(XML)
urls <- getNodeSet(htmlParse(htmldata), "//a[contains(@href, 'support.google.com')]/@href"))

使用rex可能會使這種類型的任務更簡單一些。

# generate dataset
x <- c(
"https://support.google.com/blogger/topic/12457
https://support.google.com/blogger/topic/12457.
https://support.google.com/blogger/topic/12457] 
<<https://support.google.com/blogger/topic/12457>>
https://support.google.com/blogger/topic/12457,
https://support.google.com/blogger/topic/12457),
xxxxxxhttps://support.google.com/blogger/topic/12457),hhhththta")

# extract urls
# note you don't have to worry about escaping the html string yourself
library(rex)    
re <- rex(
  capture(name = "url",
    "https://support.google.com/blogger/topic/",
    digits
    ))

re_matches(x, re, global = TRUE)[[1]]
#>                                             url
#>1 https://support.google.com/blogger/topic/12457
#>2 https://support.google.com/blogger/topic/12457
#>3 https://support.google.com/blogger/topic/12457
#>4 https://support.google.com/blogger/topic/12457
#>5 https://support.google.com/blogger/topic/12457
#>6 https://support.google.com/blogger/topic/12457
#>7 https://support.google.com/blogger/topic/12457

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM