6

正規表現を使用して、データフレーム内のテキストからすべての URL を新しい列に抽出したいと考えています。キーワードを抽出するために使用した古いコードがいくつかあるので、コードを正規表現に適合させようとしています。正規表現を文字列変数として保存し、ここに適用したい:

data$ContentURL <- apply(sapply(regex, grepl, data$Content, fixed=FALSE), 1, function(x) paste(selection[x], collapse=','))

正規表現であることfixed=FALSEがわかるはずgreplですが、Rは正規表現を次のように保存しようとしている方法が好きではありません。

regex <- "http.*?1-\\d+,\\d+"

私のデータは、次のようなデータ フレームに編成されています。

data <- read.table(text='"Content"     "date"   
 1     "a house a home https://www.foo.com"     "12/31/2013"
 2     "cabin ideas https://www.example.com in the woods"     "5/4/2013"
 3     "motel is a hotel"   "1/4/2013"', header=TRUE)

うまくいけば、次のようになります。

                                           Content       date              ContentURL
1               a house a home https://www.foo.com 12/31/2013     https://www.foo.com
2 cabin ideas https://www.example.com in the woods   5/4/2013 https://www.example.com
3                                 motel is a hotel   1/4/2013                        
4

4 に答える 4

24

適切な URL パターンを使用したHadleyverse ソリューション (stringrパッケージ):

library(stringr)

url_pattern <- "http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+"

data$ContentURL <- str_extract(data$Content, url_pattern)

data

##                                            Content       date              ContentURL
## 1               a house a home https://www.foo.com 12/31/2013     https://www.foo.com
## 2 cabin ideas https://www.example.com in the woods   5/4/2013 https://www.example.com
## 3                                 motel is a hotel   1/4/2013                    <NA>

str_extract_allに倍数がある場合は使用できますContentが、後で追加の処理が必要になります。

于 2014-10-22T00:55:36.490 に答える
3

qdapRegexライブラリを使用したアプローチの 1 つを次に示します。

library(qdapRegex)
data[["url"]] <- unlist(rm_url(data[["Content"]], extract=TRUE))
data

##                                            Content       date                     url
## 1               a house a home https://www.foo.com 12/31/2013     https://www.foo.com
## 2 cabin ideas https://www.example.com in the woods   5/4/2013 https://www.example.com
## 3                                 motel is a hotel   1/4/2013                    <NA>

関数で使用される正規表現を確認するには (正規表現のqdapRegex分析と教育を支援する目的で) grab、関数名の前に を付けて関数を使用でき@ます。

grab("@rm_url")

## [1] "(http[^ ]*)|(ftp[^ ]*)|(www\\.[^ ]*)"

greplyes this string contains または no it not の論理出力を示します。 grepインデックスまたは値を示しますが、値は文字列全体であり、必要な部分文字列です。

したがって、この正規表現を base またはstringiパッケージ ( qdapRegexは抽出のために stingi をラップします) に渡すには、次のようにします

regmatches(data[["Content"]], gregexpr(grab("@rm_url"), data[["Content"]], perl = TRUE))

library(stringi)
stri_extract(data[["Content"]], regex=grab("@rm_url"))

ストリンガーのアプローチもあると思いますが、パッケージに慣れていません。

于 2014-10-21T23:55:07.550 に答える