【问题标题】:Comparing strings word by word and row by row逐字逐行比较字符串
【发布时间】:2019-10-16 22:14:54
【问题描述】:

我有两个具有两个地址列的数据集。我想通过公共地址合并两个数据集。但是有些地址是十字路口,街道名称的顺序在每个数据集中都不同。有没有办法让 Rstudio 逐字比较字符串,如果匹配的单词超过两个,请告诉我?一个例子是:

“拉格莱斯街上的卡博特街”和“卡博特街上的拉格莱斯街”

【问题讨论】:

    标签: r string string-comparison


    【解决方案1】:

    此代码按字母顺序重新排列地址中的单词,因此您可以测试两个地址是否相同

    library(stringr)
    df =  data.frame(address = c("CABOT ST AT RUGGLES ST", "RUGGLES ST AT CABOT ST"))
    
    # split the address into words
    list_split <- str_split(df$address,' ')
    #[[1]]
    #[1] "CABOT"   "ST"      "AT"      "RUGGLES" "ST"     
    
    #[[2]]
    #[1] "RUGGLES" "ST"      "AT"      "CABOT"   "ST"
    
    # sort the words
    list_sort <- map(list_split, sort)
    #[[1]]
    #[1] "AT"      "CABOT"   "RUGGLES" "ST"      "ST"     
    
    #[[2]]
    #[1] "AT"      "CABOT"   "RUGGLES" "ST"      "ST"  
    
    # paste all the words reordered together
    list_pasted <-  map(list_sort,function(x) paste(x,collapse= " "))
    #[[1]]
    #[1] "AT CABOT RUGGLES ST ST"
    
    #[[2]]
    # [1] "AT CABOT RUGGLES ST ST"
    
    # unlist to convert to vector and assign to a new column
    df$address_sorted <- unlist(list_pasted)
    #                 address         address_sorted
    #1 CABOT ST AT RUGGLES ST AT CABOT RUGGLES ST ST
    #2 RUGGLES ST AT CABOT ST AT CABOT RUGGLES ST ST
    

    如果您有两个地址列,您可以对另一列执行相同操作并将它们一起比较

    【讨论】:

    • 谢谢,这正是我需要的!
    【解决方案2】:

    我不确定简单地将两个字符串比较两个以上的相似词是否足以解决您的问题。但是,可以使用stringr 包中的str_split 函数来完成此操作。我还添加了一种从比较中删除不需要的词的方法,例如“ST”和“AT”:

    # List of words to exclude from the comparisons
    excluded <- c("ST", "AT")
    
    # Addresses to compare
    ad_1 <- "CABOT ST AT RUGGLES ST"
    ad_2 <- "RUGGLES ST AT CABOT ST"
    
    # Get unique list of words in each address
    ad_1_d <- unique(str_split(ad_1, " ")[[1]])
    ad_2_d <- unique(str_split(ad_2, " ")[[1]])
    
    # Remove words from the vector above
    ad_1_d <- ad_1_d[!ad_1_d %in% excluded]
    ad_2_d <- ad_2_d[!ad_2_d %in% excluded]
    
    if (sum(ad_1_d %in% ad_2_d) >= 2 || sum(ad_2_d %in% ad_1_d) >= 2) {
      message("Similar addresses.")
    }
    

    【讨论】:

    • 谢谢!你的意思是这还不够?
    • @Sani:例如,“ST”和“AT”这两个地址都出现了。因此,如果我正确理解您的问题,两个地址“THING1 ST AT THING2 ST”和“THING3 ST AT THING4 ST”将在不应该匹配的情况下匹配。我通过使用“严格超过 2”而不是“2 或更多”来修复它,但您可能应该使用“ST”和“AT”等单词列表来排除比较。
    • 是的,你的理解是正确的。我需要做的是删除后缀词。在那之后,我只有“CABOT”和“RUGGLES”。感谢您的出色帮助!
    猜你喜欢
    • 1970-01-01
    • 2012-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-29
    • 2015-06-17
    • 2019-01-14
    • 1970-01-01
    相关资源
    最近更新 更多