尝试在 R 中创建正则表达式以从字符串中提取县名。当然,你不能只捕获“县”这个词前面的第一个词,因为有些县有一个 2 个或 3 个字的名称。在这个特定的数据集中,还有一些其他棘手的表达式需要解决。这是我的第一次尝试:
library(data.table)
foo <- data.table(foo=c("Unemployment Rate in Southampton County, VA"
,"Personal Income in Southampton County + Franklin City, VA"
,"Mean Commuting Time for Workers in Southampton County, VA"
,"Estimate of People Age 0-17 in Poverty for Southampton County, VA"))
foo[,county:=trimws(regmatches(foo,gregexpr("(?<=\\bfor|in\\b).*?(?=(City|Municipality|County|Borough|Census Area|Parish),)",foo,perl=T)),"both")]
如有任何帮助,我们将不胜感激!
最佳答案
另一种策略:使用可能的县名列表:
library(maps)
library(stringi)
counties <- sapply(strsplit(map("county", plot=F)$names,",",T), "[", 2)
counties <- unique(sub("(.*?):.*", "\\1", counties))
counties <- sub("^st", "st.?", counties)
foo=c("Unemployment Rate in Southampton County, VA"
,"Personal Income in Southampton County + Franklin City, VA"
,"Mean Commuting Time for Workers in Southampton County, VA"
,"Estimate of People Age 0-17 in Poverty for Southampton County, VA")
stri_extract_all_regex(
foo, paste0("\\b(", paste(counties, collapse = "|"), ")\\b(?!\\s*city)"), case_insensitive=TRUE
)
# [[1]]
# [1] "Southampton"
#
# [[2]]
# [1] "Southampton"
#
# [[3]]
# [1] "Southampton"
#
# [[4]]
# [1] "Southampton"
关于正则表达式从字符串中提取县名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43698187/