在Golang中从映射提取最优匹配的重复匹配问题求解
问题:子标头重复匹配的最优解提取错误
输入数据
{ "E-mail": { "Email": 0.8333333333333334, "Mail": 0.6666666666666667 }, "Email": { "Email": 1, "Mail": 0.8 }, "LinkedIn URL": { "LinkedIn URL": 1 } }
期望输出
需提取最高得分匹配,且子标头不能被多个父标头重复匹配,预期结果如下:
{ "E-mail": { "Mail": 0.6666666666666667 }, "Email": { "Email": 1 }, "LinkedIn URL": { "LinkedIn URL": 1 } }
实际错误输出
当前代码运行后得到错误结果,子标头Email同时匹配了E-mail和Email两个父标头:
{ "E-mail": { "Email": 0.8333333333333334 }, "Email": { "Email": 1 }, "LinkedIn URL": { "LinkedIn URL": 1 } }
问题说明
规则明确子标头不允许与多个父标头匹配,得分1的精确匹配应优先占用对应子标头,避免重复分配。当前代码未处理子标头的占用逻辑,导致高优先级的精确匹配未锁定子标头,低优先级匹配重复使用了已被占用的子标头。
当前代码
package main import ( "encoding/json" "fmt" ) func main() { input := `{ "E-mail": { "Email": 0.8333333333333334, "Mail": 0.6666666666666667 }, "Email": { "Email": 1, "Mail": 0.8 }, "LinkedIn URL": { "LinkedIn URL": 1 } }` allMatches := make(map[string]map[string]float64) if err := json.Unmarshal([]byte(input), &allMatches); err != nil { panic(err) } // ------------------------------------------------------------------------- bestMatches := make(map[string]map[string]float64) for parentHeader, matches := range allMatches { var ( bestMatchedScore float64 bestMatchedHeader string ) for childHeader, score := range matches { if score == 1 { bestMatchedScore = score bestMatchedHeader = childHeader break } if bestMatchedScore > score { continue } bestMatchedScore = score bestMatchedHeader = childHeader } bestMatches[parentHeader] = map[string]float64{ bestMatchedHeader: bestMatchedScore, } } res, err := json.MarshalIndent(bestMatches, "", " ") if err != nil { panic(err) } fmt.Println(string(res)) }
内容的提问来源于stack exchange,提问作者BentCoder
相关产品推荐
相关产品推荐

