gpt4 book ai didi

r - 从R中的字符串中匹配提取的国家名称

转载 作者:行者123 更新时间:2023-12-02 15:03:46 25 4
gpt4 key购买 nike

我一直在从网站上抓取评论数据,在此过程中我能够获得包含用户名、评论数量、评论日期和国家/地区信息的字符串向量。它们看起来大致像这样

raw <- c("Anna (1025) - North Carolina, USA - DEC 20, 2017", 
"James (10) - - MEXICO - NOV 22, 2017",
"Susane (222) - Oulu, FINLAND - JUNE 1, 2016",
"Alex (20000) - SOUTH KOREA- MAR 11, 2015")

到目前为止,我可以提取名称、评论编号和日期,因为它们位于定义的位置或具有一致的格式。问题在于国家/地区名称格式的位置不一致,并且每个字符串中的各个数据点没有一致地用逗号或破折号分隔。仅提取大写字符串会遇到缺少国家或名称包含两个部分的国家的问题。

map 包包含一个国家列表。有没有一种方法可以使用 stringr 中的 str_extract_all 在国家/地区列表向量中查找匹配项并提取匹配项?

最佳答案

您可以使用 maps 库执行此操作,如下所示:

library(maps)

## Loading country data from package maps
data(world.cities)

raw <- c("Anna (1025) - North Carolina, USA - DEC 20, 2017",
"James (10) - - MEXICO - NOV 22, 2017",
"Susane (222) - Oulu, FINLAND - JUNE 1, 2016",
"Alex (20000) - SOUTH KOREA- MAR 11, 2015")

###Removing punctuation
raw <- gsub("[[:punct:]\n]","",raw)

# Split data at word boundaries
raw2 <- strsplit(raw, " ")

# Match on country in world.countries
CountryList_raw <- (lapply(raw2, function(x)x[which(toupper(x) %in% toupper(world.cities$country.etc))]))

do.call(rbind, lapply(CountryList_raw, as.data.frame))

# X[[i]]
#1 USA
#2 MEXICO
#3 FINLAND

This works. However, you would need to fix the name of the country that has multiple words in it later. For example, in this case, SOUTH KOREA. It's because strsplit is splitting the words and this is the reason it couldn't match SOUTH KOREA.

关于r - 从R中的字符串中匹配提取的国家名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47999506/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com