【问题标题】:Detect list of items within a string检测字符串中的项目列表
【发布时间】:2021-07-02 19:53:45
【问题描述】:

我能够从 Wikipeida 中提取必要的表格(见下文)。对于每个国家,该表显示了几个毗邻的国家。对于每个国家,我想提取一个包含其邻国的列表。不幸的是,我遇到了一点麻烦,需要一些帮助。

目前的成果

Country   Neighbors
Albania   Greece

期望的结果

理想情况下,我希望国家/地区显示为列表,以便可以访问每个国家/地区的每个邻居。

Country   Neighbors
Albania   Greece; Kosovo; North Macedonia; Montenegro

任何帮助将不胜感激。 谢谢

代码(到目前为止)

library(tidyverse)
library(dplyr)
library(rvest)
library(lubridate)

# This code extracts the table and converts it to a dataframe 

xml2::read_html("https://en.wikipedia.org/wiki/List_of_countries_and_territories_by_land_borders")

land_borders <- page %>%
        html_nodes(xpath="/html/body/div[3]/div[3]/div[5]/div[1]/table") %>%
        html_table(fill=TRUE)

land_borders = data.frame(land_borders)

# Get the unique countries
unique_countries = land_borders[,1]

下面的代码为每一行提取一个国家/地区。我想提取第 6 列中的所有国家/地区并将其显示为列表。

test = list()
test <- str_extract(land_borders[,6], paste(unique_countries, collapse="|"))

【问题讨论】:

    标签: r string list


    【解决方案1】:

    使用str_extract_all提取所有国家/地区的列表,您可以使用toString将它们折叠成一个字符串。

    sapply(stringr::str_extract_all(land_borders[,6], 
           paste(unique_countries, collapse="|")), toString)
    
    #[1] ""
    #[2] "Russia, Georgia"
    #[3] "Iran, Pakistan, Tajikistan, Turkmenistan, Uzbekistan"
    #[4] "Greece, North Macedonia, Montenegro"
    #[5] "Libya, Mali, Mauritania, Morocco, Niger, Tunisia"
    #...       
    #...
    

    【讨论】:

    • 太棒了!那很完美。多谢了。完美运行
    猜你喜欢
    • 2011-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-11
    • 2017-12-03
    • 2017-05-31
    • 2019-08-11
    相关资源
    最近更新 更多