我有一個帶有街道號碼欄位的表,該欄位應該是所有數值,但資料集的創建者允許使用 567M 或 4321.5 等無效值來指示公寓號或奶奶單位。我需要將整數放入一個新欄位并將字母值和十進制值放入街道后綴欄位中。我一直在玩正則運算式和isalpha()和isalnum():
# import regex
import re
# list of values that should be all numbers
lst = ['1234', '4321.5', '567M']
# create new lists where l1 will be numeric datatypes and l2 will contain suffixes
# if there is a decimal symbol the string should be split with first value being all numbers
# and going into l1 and everything after decimal in l2
l1 = []
l2 =[]
for i in lst:
if i.isalnum(): # all characters are numeric and good to go. Maybe need to do int()?
l1.append(i)
elif '.' in i: # a decimal was found and values need to to be split and placed into two different lists
i.split(".")
l1.append(i[0])
l2.append(i[-1])
else:
if i.isnumeric() == False: # if a letter is found in a list item everything prior to letter goes to l1 and letter goes to l2
i = re.split('(\d )', i)
l1.append(i[0])
l2.append(i[-1])
運行代碼時,我立即得到了這個:
['4321', '5']
然后得到這個 forl1和l2(l1作為新的數字串列和l2字串后綴串列):
['4321', '5']
l1
['1234', '4', '567M']
l2
['5']
我在這里朝著正確的方向前進了嗎?我希望這會更簡單,但資料非常不穩定。
uj5u.com熱心網友回復:
你的第一個問題是它i.split(".")本身沒有做任何有用的事情,它回傳一個帶有分割部分的串列。您沒有使用它(似乎您的解釋器正在為您列印出來),然后您繼續索引原始的未拆分字串。您可以i = i.split(".")用來修復代碼的那部分,但在下面我建議了一個更好的方法。
另一個問題是您的正則運算式拆分代碼也不起作用。我建議使用完全不同的正則運算式方法,而不是嘗試修復它,該方法也將處理您正在查看的其他情況:
for i in lst:
match = re.match(r'(\d )\.?(.*)', i)
if match is None:
raise ValueError("invalid address format {i}")
l1.append(match.group(1))
l2.append(match.group(2))
這使用正則運算式模式來匹配您想要的街道號碼的兩個部分。任何領先的數字部分都會與第一個捕獲組匹配并放入l1,而尾隨的任何其他內容(可選地在小數點后)放入l2. 第二部分可能是一個空字串,如果沒有多余的部分街道號碼,但我還是把它放到l2,其中當您嘗試遍歷你會欣賞l1和l2在一起。
uj5u.com熱心網友回復:
您可以只使用正則運算式來進行模式匹配。該運算式將由三部分組成:
- 街道號碼:
[1-9]\d* - 一個可選的分隔符,例如 .,- :
[\.,\- ]* - 后綴(除空格之外的任何字符):
[^\s]*
import re
pattern = re.compile(r'(?P<number>[1-9]\d*)[\.,\- ]*(?P<suffix>[^\s]*)')
list = ['1234', '4321.5', '567M', ' 31-a ']
l1 = []
l2 = []
for item in list:
match = pattern.search(item)
if match:
l1.append(int(match.group('number')))
l2.append(match.group('suffix'))
print(f'l1: {l1}')
print(f'l2: {l2}')
結果:
l1: [1234, 4321, 567, 31]
l2: ['', '5', 'M', 'a']
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/355941.html
上一篇:用另一組替換一組
下一篇:驗證字串是否與正則運算式匹配
