我正在使用一個函式來拆分下面的示例行以洗掉獨立的數值 (123),但它也洗掉了我需要的尾隨數字。我也不知道如何洗掉“0.0”
ABC/0.0/123/TT1/1TT//
cleaned_data = []
def split_lines(lines, delimiter, remove = '[0-9] $'):
for line in lines:
tokens = line.split(delimiter)
tokens = [re.sub(remove, "", token) for token in tokens]
clean_list = list(filter(lambda e:e.strip(), tokens))
cleaned_data.append(clean_list)
print(clean_list)
split_lines(lines, "/")
現在出現的內容如下,注意 0. 和缺少尾隨 1 的“TT”。
[ABC]、[0.]、[TT]、[1TT]
uj5u.com熱心網友回復:
你真的需要正則運算式嗎?str.split()如果您只是使用并嘗試將結果值轉換為,這項作業會簡單得多float:
def split_lines_remove_numeric(lines, delimiter):
for line in lines:
clean_list = []
for item in line.split(delimiter):
if not item: continue # Skip this item if it's empty
try:
# Convert to float
float(item)
except ValueError: # Enter this block if conversion threw an error
clean_list.append(item)
print(clean_list)
然后,呼叫此函式會洗掉您想要的值:
>>> split_lines_remove_numeric(["ABC/0.0/123/TT1/1TT//"], "/")
['ABC', 'TT1', '1TT']
uj5u.com熱心網友回復:
嘗試也包括行錨 (^) 的開頭。
cleaned_data = []
def split_lines(lines, delimiter, remove = '^[0-9.] $'):
for line in lines:
tokens = line.split(delimiter)
tokens = [re.sub(remove, "", token) for token in tokens]
clean_list = list(filter(lambda e:e.strip(), tokens))
cleaned_data.append(clean_list)
print(clean_list)
split_lines(lines, "/")
我只是將引數的默認值更改remove為 '^[0-9.] $',僅當整個搜索字串是數字(或句點)時才匹配。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/470311.html
標籤:Python python-3.x 功能 蟒蛇重新
