假設我有這些資料
data = '''a, b, c
d, e, f
g. h, i
j, k , l
'''
第 4 行包含一個空格,第 6 和第 7 行不包含任何空格,只是一個空白的新行。
現在,當我使用相同的拆分splitlines
data.splitlines()
我明白了
['a, b, c', 'd, e, f', 'g. h, i', ' ', 'j, k , l', '', '']
然而預期只是
['a, b, c', 'd, e, f', 'g. h, i', 'j, k , l']
有沒有使用正則運算式的簡單解決方案來做到這一點。
請注意,我知道通過從輸出中過濾空字串來做同樣的事情的另一種方法splitlines()
我不確定使用正則運算式是否可以實作相同的目標。
當我使用正則運算式在新行上拆分時,它給了我
import re
re.split("\n", data)
輸出 :
['a, b, c', 'd,e,f', 'g. h, i', ' ', 'j, k , l', '', '', '']
uj5u.com熱心網友回復:
我不同意您的評估,即過濾比使用正則運算式更復雜。但是,如果您真的想使用正則運算式,您可以像這樣在多個連續的換行符處拆分:
>>> re.split(r"\n ", data)
['a, b, c', 'd, e, f', 'g. h, i', 'j, k , l', '']
不幸的是,這會在串列末尾留下一個空字串。要解決此問題,請使用re.findall查找所有不是換行符的內容:
>>> re.findall(r"([^\n] )", data)
['a, b, c', 'd, e, f', 'g. h, i', 'j, k , l']
由于該正則運算式不適用于帶有空格的輸入,因此這里有一個:
>>> re.findall(r"^([ \t]*\S.*)$", data, re.MULTILINE)
['a, b, c', 'd, e, f', 'g. h, i', 'j, k , l ']
下面是解釋:
^([ \t]*\S.*)$
^ $ : Start of line and end of line
( ) : Capturing group
[ \t]* : Zero or more of blank space or tab (i.e. whitespace that isn't newline
\S : One non-whitespace character
.* : Zero or more of any character
uj5u.com熱心網友回復:
串列理解方法
如果元素不是空字串或帶有條件檢查的空白字串,您可以將元素添加到串列中。
如果元素/行是True在從空格中洗掉它之后,那么它與空字串不同,因此您將其添加到串列中。
filtered_data = [el for el in data.splitlines() if el.strip()]
# ['a, b, c', 'd, e, f', 'g. h, i', 'j, k , l']
正則運算式方法
import re
p = re.compile(r"^([^\s] . )", re.M)
p.findall(data)
# ['a, b, c', 'd, e, f', 'g. h, i', 'j, k , l']
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/492589.html
下一篇:R-使用函式基于字串比較創建新列
