如何在python中刪除郵政編碼中的+4?在郵編中刪除 - ####
我有數據,如
85001
52804-3233
Winston-Salem
而且我想,要成爲
85001
52804
Winston-Salem
如何在python中刪除郵政編碼中的+4?在郵編中刪除 - ####
我有數據,如
85001
52804-3233
Winston-Salem
而且我想,要成爲
85001
52804
Winston-Salem
>>> zip = '52804-3233'
>>> zip[:5]
'52804'
...當然,當你從你要把原始數據解析你的線條插入一些規則來區分郵編到修正和其他字符串,但我不知道你的數據是怎麼樣的,所以我不能幫忙(你可以檢查它們是否只有數字和' - '符號,也許?)。
>>> import re
>>> s = "52804-3233"
>>> # regex to remove a dash and 4 digits after the dash after 5 digits:
>>> re.sub('(\d{5})-\d{4}', '\\1', s)
'52804'
的\\1
是所謂的反向引用,並得到由第一組,這將是在這種情況下,5位郵政編碼取代。
這抓起格式00000-0000
用空格或其他單詞邊界的所有項目前後的編號,與前五位數字替換它。發佈的其他正則表達式將匹配您可能不需要的其他數字格式。
re.sub('\b(\d{5})-\d{4}\b', '\\1', zipcode)
或者沒有正則表達式:
output = [line[:5] if line[:5].isnumeric() and line[6:].isnumeric() else line for line in text if line]
你試過到目前爲止有什麼解決辦法嗎? – Thomas