如何实现地址中单/双词郊区的字典匹配替换?
地址中单/双词郊区的替换实现方案
需求说明
需要替换地址行中的单/双词郊区,将字典中的键与地址行内容匹配后,替换为对应的字典值。示例如下:
输入:
32 Konini Street Eastbourne Retired 6 Moana Road Days Bay Retailer
期望输出:
32 Konini Street _Eastbourne Retired 6 Moana Road _Days_Bay Retailer
现有代码
# Parsing words of line for single/double word dictionary key # replacing found instances with underscore version lines = ['6 Moana Road Days Bay Retailer','32 Konini Street Eastbourne Retired'] sampleDictionary = {"Days Bay":"_Days_Bay","Eastbourne":"_Eastbourne"} newString = '' doubleWordLists = [] for i in range(len(lines)): line = lines[i] splits = line.split(' ') # Unused block for j in range(len(splits)): if j + 1 < len(splits): doubleWord = splits[j] + ' ' + splits[j + 1] doubleWordLists.append(doubleWord) # Compare a token with dictionary. If no match compare that token and next. # Add appropriate token(s) to new string for j in range(len(splits)): if splits[j] != '\d': for key in sampleDictionary: value = sampleDictionary[key] if key == splits[j]: newString += value + ' ' else: #if key == doubleWordLists[j]: # newString += value + ' ' newString += splits[j] + ' ' else: newString += splits[j] + ' ' print(newString)
现有输出
6 Moana Road Days Bay Retailer 32 Konini Street _Eastbourne Retired
问题描述
我尝试用doubleWordLists匹配并替换字符串中的双词郊区(见注释代码),但没法在splits[j]的索引范围内完成操作。当前核心问题是:如何实现双词字典键的匹配,并把对应字典值正确替换到字符串的对应位置?
解决方案
你的代码存在两个核心问题:一是字典遍历逻辑错误,循环结束后key只会保留最后一个字典键;二是双词匹配时没有处理索引跳转,导致无法跳过已匹配的第二个单词。以下是修正后的实现思路和代码:
- 优先匹配长键:将字典键按拆分后的单词数量从多到少排序,优先匹配双词,避免单词匹配干扰双词的完整匹配
- 灵活控制索引:使用
while循环遍历拆分后的单词列表,匹配到双词时直接跳过下一个索引,避免重复处理 - 逐行独立处理:每一行处理完成后单独输出,避免所有行内容混在一个字符串中
修正后的代码
lines = ['6 Moana Road Days Bay Retailer','32 Konini Street Eastbourne Retired'] sampleDictionary = {"Days Bay":"_Days_Bay","Eastbourne":"_Eastbourne"} # 按键的单词数量降序排序,优先匹配双词 sorted_keys = sorted(sampleDictionary.keys(), key=lambda k: len(k.split()), reverse=True) for line in lines: word_list = line.split(' ') result = [] index = 0 while index < len(word_list): # 尝试匹配当前及下一个单词组成的双词 if index + 1 < len(word_list): current_double_word = f"{word_list[index]} {word_list[index+1]}" if current_double_word in sampleDictionary: result.append(sampleDictionary[current_double_word]) index += 2 # 跳过下一个单词,已匹配双词 continue # 匹配单词 current_single_word = word_list[index] if current_single_word in sampleDictionary: result.append(sampleDictionary[current_single_word]) else: result.append(current_single_word) index += 1 # 拼接结果并打印 print(' '.join(result))
运行结果
6 Moana Road _Days_Bay Retailer 32 Konini Street _Eastbourne Retired
内容的提问来源于stack exchange,提问作者Dave
相关产品推荐
相关产品推荐

