[英]String replacement loop using Python dictionary
有人可以建議從字典中進行迭代字符串替換的最佳方法嗎?
我將向下瀏覽一列地址,如下所示:
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"
等。
我不太能用相應的鍵替換語法。
你試過了嗎?:
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
這是一個解決方案的草圖。
您應該使用從字符串到字符串列表的字典,例如
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
可能更干凈的解決方案是僅在輸入上使用替換正則表達式的映射。 例如
conversions = {
'/court_pattern_here/': 'CT',
'/drive_pattern_here/': 'DR'
}
接着:
for regex, replacement in conversions.items():
input = input.replace(regex, replacement)
您可以使用活動狀態字典反轉代碼段預先構建反向字典
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] )
這是一個示例,可能會有所幫助。 你的旅費可能會改變。
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)
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
謝謝大家的幫助。 這就是我最后得到的。
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')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.