2017-12-06 13 views
-1

私は国連ウェブサイトのWFPからRでウェブを吟味し、食糧安全保障に関するアップデート(http://www.fao.org/countryprofiles/en/)を含むデータセットを構築しています。 パッケージは、rvest、stringr、tidyr、data.table、plyr、xml2、jsonliteです。 しかし、データセットの国名、記事のURL、記事のタイトル、記事のテキストをインポートしました。 解析を簡単にするため、興味のあるキーワード(例:「食料安全保障」、「干ばつ」など)を含む新しい変数を設定し、前述のキーワードの通貨を記録します。 その変数は私の研究を非常に単純化します。 提案がありますか?Rウェブスクレイピング設定キーワード

ここでは私が使用している基本コードを示します。

## 01. Creating a function in order to scrape data from a website (in this case, FAO's) 

WFP_get_news <- function(countries) {              GET(
url = "http://www1.wfp.org/countries/common/allnews/en/", 
query = list(countries=countries) 
) -> res 

warn_for_status(res) 

if (status_code(res) > 399) return(NULL) 

out <- content(res, as="text", encoding="UTF-8") 
out <- jsonlite::fromJSON(out) 
out$countries <- countries 

tbl_df(out) 
} 


## 02. Setting all the Country urls in order for them to be automatically scraped 

pb <- progress_estimated(length(countrycode_data$countries[])) 
map_df(countrycode_data$countries[], ~{ 
pb$tick()$print() 
Sys.sleep(5) 
wfp_get_news(.x) 
}) -> xdf 



## 03. Setting keywords (of course, this process is arbitrary: one can decide any keywor s/he prefers) 
keywords <- c("drought", "food security")           


keyword_regex <- sprintf("(%s)", paste0(keywords, collapse="|")) 


## 04. Setting the keywords search 
bind_cols(                     
xdf, 
stri_match_all_regex(tolower(xdf$bodytext), keyword_regex) %>% 
map(~.x[,2]) %>% 
map_df(~{ 
res <- table(.x, useNA="always") 
nm <- names(res) 
nm <- ifelse(is.na(nm), "NONE", stri_replace_all_regex(nm, "[ -]", "_")) 
as.list(set_names(as.numeric(res), nm)) 
}) 
) %>% 
select(-NONE) -> xdf_with_keyword_counts 

私はポイント04から取得した結果は

Error in overscope_eval_next(overscope, expr) : 
object "NONE" not found 
Furthermore: Warning message: 
Unknown or uninitialised column: 'data.frame'. 

任意の手がかりとなりますか?

+0

あなたはポストこするデータ '言及したキーワードに基づいてデータをフィルタリングすることができ、私たちにあなたが –

+0

より良い – Ileeo

+1

上向きのコードを示すのを助けるためにしようとしているコードを表示してくださいgrep() 'などが役立つはずです。そのアプローチに問題はありますか? – abhiieor

答えて

0

まず、2〜3倍にカット/ペーストすると機能が維持されるという一般的なルールがあります。

我々はいくつかの助けが必要になるでしょう:

library(countrycode) 
library(httr) 
library(rvest) 
library(stringi) 
library(tidyverse) 

は、ここであなたが望むあなたがデータを取得するためにiso3コードを呼び出すことができる機能[フレーム]です:

fao_get_news <- function(iso3) { 

    GET(
    url = "http://www.fao.org/countryprofiles/common/allnews/en/", 
    query = list(iso3=iso3) 
) -> res 

    warn_for_status(res) 

    if (status_code(res) > 399) return(NULL) 

    out <- content(res, as="text", encoding="UTF-8") 
    out <- jsonlite::fromJSON(out) 
    out$iso3 <- iso3 

    tbl_df(out) 

} 

、我々は繰り返しますすべてiso3コードを持ち、countrycodeパッケージのヘルパーデータフレームを使用します。

注:次の2行で[1:20]を削除して、すべてのデータを取得する必要はありません。時間/帯域幅を消費しません。あなたがabtの倫理を全く気にかけているのであれば、禁止されたり、非営利団体のサーバーを叩いたりしないでください。Sys.sleep(5)をそこに保管してください。もしあなたが利己的であれば、それでもあなたのニーズはFAOのものではありません。

glimpse(xdf) 
## Observations: 736 
## Variables: 10 
## $ uid   <chr> "1069933", "1069560", "1045264", "1044139", "103833... 
## $ table  <chr> "news", "news", "news", "news", "news", "news", "ne... 
## $ title  <chr> "FAO Calls for Stronger Collaboration on Transbound... 
## $ date  <chr> "1511823600", "1511737200", "1508191200", "15081048... 
## $ bodytext <chr> "28 November 2017- Chief Veterinary Officers and ex... 
## $ date_format <chr> "28/11/2017", "27/11/2017", "17/10/2017", "16/10/20... 
## $ image  <chr> "http://www.fao.org/fileadmin/user_upload/rne/img/I... 
## $ pid   <chr> "50840", "16275", "70992", "16275", "2330", "40990"... 
## $ detail_pid <chr> "/neareast/news/view/en/c/1069933/", "/asiapacific/... 
## $ iso3  <chr> "AFG", "AFG", "AFG", "AFG", "AFG", "AFG", "AFG", "A... 

置くすべてのキーワード(小文字)ここに:

keywords <- c("drought", "food security") 
私たち( iso3フィールドを持つ)すべてのニュースとの素敵な、きちんとしたデータフレームを与える

pb <- progress_estimated(length(countrycode_data$iso3c[1:20])) 
map_df(countrycode_data$iso3c[1:20], ~{ 
    pb$tick()$print() 
    Sys.sleep(5) # no crawl delay specified in site robots.txt so this is the ethical default 
    fao_get_news(.x) 
}) -> xdf 

正規表現を構築します

keyword_regex <- sprintf("(%s)", paste0(keywords, collapse="|")) 

今、既存のデータフレームにキーワード列を追加します。

  • 小文字のニュースブロブ
  • ニュースブロブ
  • キャプチャAに各キーワード(もしあれば)のすべての出現を見つける:stri_match… ++がやっていることの概要については、各ニュースブロブのためということですキーワード
  • と一緒に出現#の数(軽く)キーワードは有効な列名
  • は、任意のキーワードを指定しない
  • 塊だけでを持っています見つかった各キーワードの新しい列を作ることができることを確認見つかったカウント値については

我々は、キーワードの結果データフレームcount()spread()を作ることができますが、それはない高速動作です。 table()を使用するともう少しタイピングが可能ですが、はるかに速い結果が得られます。

bind_cols(
    xdf, 
    stri_match_all_regex(tolower(xdf$bodytext), keyword_regex) %>% 
    map(~.x[,2]) %>% 
    map_df(~{ 
     res <- table(.x, useNA="always") 
     nm <- names(res) 
     nm <- ifelse(is.na(nm), "NONE", stri_replace_all_regex(nm, "[ -]", "_")) 
     as.list(set_names(as.numeric(res), nm)) 
    }) 
) %>% 
    select(-NONE) -> xdf_with_keyword_counts 

はここでの結果です:

glimpse(xdf_with_keyword_counts) 
## Observations: 736 
## Variables: 12 
## $ uid   <chr> "1069933", "1069560", "1045264", "1044139", "1038339", "... 
## $ table   <chr> "news", "news", "news", "news", "news", "news", "news", ... 
## $ title   <chr> "FAO Calls for Stronger Collaboration on Transboundary A... 
## $ date   <chr> "1511823600", "1511737200", "1508191200", "1508104800", ... 
## $ bodytext  <chr> "28 November 2017- Chief Veterinary Officers and experts... 
## $ date_format <chr> "28/11/2017", "27/11/2017", "17/10/2017", "16/10/2017", ... 
## $ image   <chr> "http://www.fao.org/fileadmin/user_upload/rne/img/IMG_64... 
## $ pid   <chr> "50840", "16275", "70992", "16275", "2330", "40990", "40... 
## $ detail_pid <chr> "/neareast/news/view/en/c/1069933/", "/asiapacific/news/... 
## $ iso3   <chr> "AFG", "AFG", "AFG", "AFG", "AFG", "AFG", "AFG", "ALA", ... 
## $ food_security <int> NA, NA, 2, 1, NA, 1, NA, NA, NA, 1, NA, NA, NA, NA, 1, N... 
## $ drought  <int> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, ... 
+0

ありがとう!これは私のものよりも面白く面白いです。私は確かにそれを使用します!感謝万円! – Ileeo

+0

私は 'PB <実行すると - progress_estimated(長さ(countrycode_data $ ISO3))' を私は.subset2に次のエラーメッセージ 'エラー(public_bind_env、 "初期化")(...)を取得: 怠惰な負荷をデータベース '/home/.../Rdata.rdbは' 壊れている Inoltre:警告メッセージ: 1:.subset2(public_bind_env、 "初期化")(...)では: 再起動が約束の評価を中断 2 :.subset2(public_bind_env、 "initialize")(...): 内部エラー-3 in R_decompress1' – Ileeo

+0

は、1つ以上のpkgがうまくインストールされていないように聞こえます。最高のアドバイスは完全にRを終了することです。パッケージを再インストールしてから再起動してください。 – hrbrmstr

関連する問題