2016-06-09 646 views
1

我想從文本中提取地名並將它們在地圖上進行地理定位 - 自動使用R.第一步是提取地名。如何從文本中提取列出的名稱(地名)?

我下載了地名列表(來自geonames);但是如何在文本內匹配geonames-placename-list中的單詞?

intersect()的可能性只有在我將文本轉換爲矢量時才起作用,因此需要將文本拆分爲單詞,從而導致匹配運算符只能找到像「柏林」這樣的單字地名但不是「紐約」等。

是否存在函數來比較一個列表與文本(作爲字符串)?

MWE:

list = c("Wien", "London", "New York") 
text = "Er sah den Stadtplan von Wien in New York." 
words = unlist(strsplit(text, "\\W")) 
intersect(list, words) 

結果只有:

> [1] "Wien" 

回答

0

你可以使用類似的東西

library(stringr) 
    list = c("Wien", "London", "New York") 
    text = "Er sah den Stadtplan von Wien in New York." 
    words=as.character() 

    for (i in 1:length(list)){ 

     if (is.na(str_extract(text,list[i]))) next 

     x<-str_extract(text,list[i]) 
     words<-c(words,x) 
    } 


    > words 
    [1] "Wien"  "New York" 
+0

謝謝!實際上,你幫助我的答案是'str_extract()'命令。我的主要觀點是從'unlist(str_extract_all(text,list))得到輸出' - 謝謝! – dia

0

根據複雜性,你也可以使用(注意有空格)

list = c("Wien", "London", "NewYork") 
text = "Er sah den Stadtplan von Wien in NewYork." 
words = unlist(strsplit(text, "\\W")) 
list[list %in% words] 

"Wien" "NewYork"