【问题标题】:Getting the closest string matches between two lists获取两个列表之间最接近的字符串匹配
【发布时间】:2019-09-22 09:50:02
【问题描述】:

我是 R 的真正初学者,我只有这两个列表,其中包含城市名称。一个列表包含用户生成的名称(人们拼写混乱),另一个列表包含名称的拼写。

我尝试使用包stringdist,最后我得到了一个循环(for)并给出最接近匹配的代码。但是我只能输入向量,我真的需要使用数据框。

这是我的代码(天哪,感觉很别扭):

 input <- "BAC"   #misspelled 
  correct <- c("ABC", "DEF", "GHI", "JKL") #list with all correct names
  shortest <- -1a

for (word in correct) {

  dist <- stringdist(input, word)
  #checks if it's a match!
  if (dist == 0){
    closest <- palavra
    shortest <- 0

    break

  }

  if(dist <= shortest || shortest < 0){
    closest <- word
    shortest <- dist

  }

}


if(shortest == 0){ 
  print("It's a match!")
} else {
  print(closest)
}

这个想法是使用这段代码来产生一个想法,我想从这个开始到在我的数据框的每一行中使用 stringdist。我什至不知道这是否是个好主意,如果这需要太多的处理能力,不要害怕说它很愚蠢。谢谢!

【问题讨论】:

  • 您的stringdist 调用中有word,但它下方的if 声明中有palavra。您是否忘记翻译“palavra”,或者它是您代码中其他地方的对象?
  • @camille 是的,我确实忘记翻译了...

标签: r dataframe spell-checking stringdist


【解决方案1】:

stringdist 包中有一个特殊的函数,叫做amatch

input <- "BAC"   #misspelled 
correct <- c("ABC", "DEF", "GHI", "JKL") 

correct[amatch(input, correct, maxDist = Inf)]
# "ABC"

这也可以同时处理多个输入词,因此无需使用 for 循环

input <- c("New Yorkk", "Berlyn", "Pariz") # misspelled 
correct <- c("Berlin", "Paris", "New York", "Los Angeles") # correct names

correct_words <- correct[amatch(input, correct, maxDist = Inf)]
data.frame(input, correct_words)

 #       input correct_words
 #   New Yorkk      New York
 #      Berlyn        Berlin
 #       Pariz         Paris

【讨论】:

    猜你喜欢
    • 2011-08-17
    • 1970-01-01
    • 1970-01-01
    • 2015-09-29
    • 1970-01-01
    • 2017-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多