我正在尝试从R中的一些文本中提取湖泊的名称。湖泊是适当的(大写的),但需要我在单词"Lake“的两边提取几个单词。
我尝试了一些东西,但没有一样东西能像我想的那样工作……在某些情况下,句子或文章可能以"Lake“开头,因此前面没有文本。在某些情况下,正确的名称可能是3个单词(Lake St.Clair或Red Hawk Lake)。
要使用的示例代码:
text <- paste("Lake Erie is located on the border of the United States and Canada.",
"It is located nearby to Lake St. Clair and Lake Michigan.",
"All three lakes have a history of high levels of Phosphorus.",
"One lake that has not yet been impacted is Lake Ontario.")这可能是我得到的最接近的结果--从另一个堆栈溢出中拉出,但它仍然不起作用。
context <- function(text){splittedText <-strsplit(text,'',T) print(splitted Text) data.frame(before = head(c('',splittedText),-1),words=splittedText,after=tail(c(splittedText,''),-1))}
info <- context(text)
print(subset(info, words == 'Lake')我想要: 1)提取正确的湖泊名称("Lake Erie“、"Lake St.Clair”等)。或者2)包含"Lake“前后单词的数据帧。理想情况下是第一个,但我在这一点上是灵活的。
before <- c("","nearby to", "Clair and","impacted is")
Lake <- c("Lake","Lake","Lake","Lake")
after <- c("Erie is","St. Clair", "Michigan ","Ontario ")
output <- data.frame(cbind(before,Lake,after)); print(output)提前感谢您的帮助!
发布于 2019-12-03 10:34:19
你需要定义一些规则来根据你拥有的数据来提取单词。这里我得到了单词"Lake"之后的第一个单词。
stringr::str_extract_all(text, "Lake \\w+")[[1]]
#[1] "Lake Erie" "Lake St" "Lake Michigan" "Lake Ontario" 或者类似地在碱基R中
regmatches(text, gregexpr("Lake \\w+", text))[[1]]对于给定的text,这几乎是可行的,除了"Lake St. Clair",因为它缺少"Clair"部分。为了处理这个问题,我们可以定义另一个规则,如果"Lake"的下一个单词后面有一个点,我们提取两个单词,但对于"Lake Michigan"和"Lake Ontario"来说,这将失败,因为它们在单词后面有句号。
发布于 2019-12-03 14:28:34
使用stringi,我们可以使用
library(stringi)
stri_extract_all_regex(text, "Lake\\s+\\w+")[[1]]
#[1] "Lake Erie" "Lake St" "Lake Michigan" "Lake Ontario" 或者使用str_match_all
library(stringr)
str_match_all(text, "Lake\\s+\\w+")[[1]][,1]https://stackoverflow.com/questions/59149336
复制相似问题