首页 > 解决方案 > 如何用空格分割字符串的字符,然后用特殊字符和数字分割列表的结果元素,然后再次加入它们?

问题描述

所以,我想要做的是将字符串中的一些单词转换为字典中它们各自的单词并保持原样。例如,输入如下:

standarisationn("well-2-34 2   @$%23beach bend com")

我想要输出为:

"well-2-34 2 @$%23bch bnd com"

我使用的代码是:

def standarisationn(addr):
a=re.sub(',', ' ', addr)
lookp_dict = {"allee":"ale","alley":"ale","ally":"ale","aly":"ale",
              "arcade":"arc",
               "apartment":"apt","aprtmnt":"apt","aptmnt":"apt",
               "av":"ave","aven":"ave","avenu":"ave","avenue":"ave","avn":"ave","avnue":"ave",
              "beach":"bch",
              "bend":"bnd",
              "blfs":"blf","bluf":"blf","bluff":"blf","bluffs":"blf",
              "boul":"blvd","boulevard":"blvd","boulv":"blvd",
              "bottm":"bot","bottom":"bot",
              "branch":"br","brnch":"br",
              "brdge":"brg","bridge":"brg",
              "bypa":"byp","bypas":"byp","bypass":"byp","byps":"byp",
              "camp":"cmp",
              "canyn":"cny","canyon":"cny","cnyn":"cny",
              "southwest":"sw" ,"northwest":"nw"}

temp=re.findall(r"[A-Za-z0-9]+|\S", a)
print(temp)
res = []
for wrd in temp:
     res.append(lookp_dict.get(wrd,wrd))
res = ' '.join(res)
return str(res) 

但它给出了错误的输出:

'well - 2 - 34 2 @ $ % 23beach bnd com'

那是空格太多,甚至没有将“海滩”转换为“bch”。所以,这就是问题所在。我认为首先用空格分割字符串,然后用特殊字符和数字分割结果元素,然后使用字典,然后首先用不带空格的特殊字符连接分隔的字符串,然后用空格连接所有列表。任何人都可以建议如何解决这个问题或任何更好的方法吗?

标签: pythondictionaryjoinsplitre

解决方案


您可以使用字典的键构建正则表达式,确保它们不包含在另一个单词中(即不直接在字母之前或之后):

import re
def standarisationn(addr):
    addr = re.sub(r'(,|\s+)', " ", addr)
    lookp_dict = {"allee":"ale","alley":"ale","ally":"ale","aly":"ale",
                "arcade":"arc",
                "apartment":"apt","aprtmnt":"apt","aptmnt":"apt",
                "av":"ave","aven":"ave","avenu":"ave","avenue":"ave","avn":"ave","avnue":"ave",
                "beach":"bch",
                "bend":"bnd",
                "blfs":"blf","bluf":"blf","bluff":"blf","bluffs":"blf",
                "boul":"blvd","boulevard":"blvd","boulv":"blvd",
                "bottm":"bot","bottom":"bot",
                "branch":"br","brnch":"br",
                "brdge":"brg","bridge":"brg",
                "bypa":"byp","bypas":"byp","bypass":"byp","byps":"byp",
                "camp":"cmp",
                "canyn":"cny","canyon":"cny","cnyn":"cny",
                "southwest":"sw" ,"northwest":"nw"}

    for wrd in lookp_dict:
        addr = re.sub(rf'(?:^|(?<=[^a-zA-Z])){wrd}(?=[^a-zA-Z]|$)', lookp_dict[wrd], addr)
    return addr

print(standarisationn("well-2-34 2   @$%23beach bend com"))

该表达式分为三个部分:

  • ^匹配字符串的开头
  • (?<=[^a-zA-Z])是一个lookbehind(即非捕获表达式),检查前面的字符是一个字母
  • {wrd}是你字典的键
  • (?=[^a-zA-Z]|$)是前瞻(即非捕获表达式),检查后面的字符是字母还是字符串的结尾

输出:

well-2-34 2 @$%23bch bnd com

编辑:如果将循环替换为以下内容,则可以编译整个表达式并仅使用 re.sub 一次:

repl_pattern = re.compile(rf"(?:^|(?<=[^a-zA-Z]))({'|'.join(lookp_dict.keys())})(?=([^a-zA-Z]|$))")
addr = re.sub(repl_pattern, lambda x: lookp_dict[x.group(1)], addr)

如果您的字典增长,这应该会快得多,因为我们使用您的所有字典键构建了一个表达式:

  • ({'|'.join(lookp_dict.keys())})被解释为(allee|alley|...
  • re.sub 中的 lambda 函数将匹配元素替换为 lookp_dict 中的相应值(有关此内容的更多详细信息,请参见此链接)

推荐阅读