使用Python字典的字符串替换循环

时间:2017-04-14 20:36:00

标签: python

有人可以建议从字典中进行迭代字符串替换的最佳方法吗?

我要去一列地址,如下所示:

Address1=" 122 S 102 ct,"

我的转换逻辑为:

CT=['ct','ct,','ct.','court']
DR=['drive,','drive.','drive','driv','dr,','dr.','dr']
dictionary={"CT":CT, "DR":DR}

我应该如何在Address1中搜索所有词典值并用相应的键替换它们?

目标是让" 122 S 102 ct,"成为" 122 S 102 CT"等等。

我无法用相应的密钥替换语法。

6 个答案:

答案 0 :(得分:1)

你试过吗?:

Splits = Address1.split("")
for i in Splits:
    if i in CT:
        i = 'CT'
    if i in DR:
        i = 'DR'

print(" ".join(Splits))  # " " will keep the spacing between words

答案 1 :(得分:1)

以下是解决方案草图。

采用原创方法

您应该使用从字符串到字符串列表的字典,例如

conversions = {
    'CT': [ 'ct', 'ct,' 'ct.', 'court' ],
    'DR': [ 'drive', 'drive.', 'driv', 'dr', 'dr.' ]
}

现在,您可以逐步浏览输入中的每个单词,并替换它:

def get_transformed_address(input):
    result = ''
    for word in input.split(' ')
        result += ' ' + maybe_convert(word)

    return result

maybe_convert()的位置:

def maybe_convert(phrase):
    for canonical, representations in conversions.items():
        if representations.contains(phrase):
            return canonical

    # default is pass-through of input
    return phrase

使用Regex

可能更简洁的解决方案是在输入上使用替换正则表达式的映射。 e.g。

conversions = {
    '/court_pattern_here/': 'CT',
    '/drive_pattern_here/': 'DR'
}

然后:

for regex, replacement in conversions.items():
    input = input.replace(regex, replacement)

答案 2 :(得分:1)

您可以使用activestate字典反转片段预构建逆字典

http://code.activestate.com/recipes/415100-invert-a-dictionary-where-values-are-lists-one-lin/

def invert(d):
   return dict( (v,k) for k in d for v in d[k] ) 

答案 3 :(得分:1)

这是一个可能有用的示例。您的里程可能会有所不同。

CT=['ct','ct,','ct.','court']
DR=['drive,','drive.','drive','driv','dr,','dr.','dr']
dictionary={"CT":CT, "DR":DR}
address1 =' 122 S 102 ct,'

我们首先查看每个键和匹配值(即您的元素列表)。 然后,我们迭代值中的每个元素,并检查元素是否存在。如果是......我们然后使用替换方法用字典中的键替换有问题的元素。

for key, value in dictionary.items():
    for element in value:
        if element in address1:
            address_new = address1.replace(element, key)
print(address_new) 

答案 4 :(得分:1)

from string import punctuation

def transform_input(column):
  words = column.rstrip(punctuation).split()
  for key, values in conversions.items():
      for ind, word in enumerate(words):
          if word in values:
            words[ind] = key
  return ' '.join(words)


Address1=" 122 S 102 ct,"

conversions = {
    'CT': [ 'ct', 'ct,' 'ct.', 'court' ],
    'DR': [ 'drive', 'drive.', 'driv', 'dr', 'dr.' ]
}

print(transform_input(Address1)) # 122 S 102 CT

答案 5 :(得分:0)

感谢大家的帮助。这就是我最终的目标。

    import pandas as pd
    import re 

    inputinfo="C:\\path"
    data=pd.DataFrame(pd.read_excel(inputinfo,parse_cols ="A",converters={"A":str}))

    TRL=['trl']
    WAY=['wy']                                                                 #do before HWY
    HWY=['hwy','hy']
    PATH=['path','pth']
    LN=['lane','ln.','ln']
    AVE=['avenue','ave.','av']
    CIR=['circle','circ.','cir']
    TER=['terrace','terace','te']
    CT=['ct','ct,','ct.','court']
    PL=['place','plc','pl.','pl']
    CSWY=['causeway','cswy','csw']
    PKWY=['parkway','pkway','pkwy','prkw']
    DR=['drive,','drive.','drive','driv','dr,','dr.','dr']
    PSGE=['passageway','passage','pasage','pass.','pass','pas']
    BLVD=['boulevard','boulevar','blvd.','blv.','blvb','blvd','boul','bvld','bl.','blv','bl']

    regex=r'(\d)(th)|(\d)(nd)|(3)(rd)|(1)(st)'
    Lambda= lambda m: m.group(1) if m.group(1) else m.group(3) if m.group(3) else m.group(5) if m.group(5)else m.group(7) if m.group(7) else ''
# the above takes care of situations like "123 153*rd* st"

    for row in range(0,data.shape[0]):
            String = re.sub(regex,Lambda,str(data.loc[row,"Street Name"]))
            Splits = String.split(" ")
            print (str(row)+" of "+str(data.shape[0]))
            for i in Splits:
                    ind=Splits.index(i)
                    if i in AVE:
                            Splits[ind]="AVE"
                    if i in TRL:
                            Splits[ind]="TRL"
                    if i in WAY:
                            Splits[ind]="WAY"
                    if i in HWY:
                            Splits[ind]="HWY"
                    if i in PATH:
                            Splits[ind]="PATH"
                    if i in TER:
                            Splits[ind]="TER"
                    if i in LN:
                            Splits[ind]="LN"
                    if i in CIR:
                            Splits[ind]="CIR"
                    if i in CT:
                            Splits[ind]="CT"
                    if i in PL:
                            Splits[ind]="PL"
                    if i in CSWY:
                            Splits[ind]="CSWY"
                    if i in PKWY:
                            Splits[ind]="PKWY"
                    if i in DR:
                            Splits[ind]="DR"
                    if i in PSGE:
                            Splits[ind]="PSGE"
                    if i in BLVD:
                            Splits[ind]="BLVD"  
            data.loc[row,"Street Name Modified"]=(" ".join(Splits))

    data.to_csv("C:\\path\\StreetnameSample_output.csv",encoding='utf-8')