我有一個包含 2 個短語的字串,由同一字串中的大寫單詞分隔:
c="Text is here. TEST . More text here also"
我想分開這兩個短語,洗掉大寫單詞,TEST這樣輸出看起來像:
["Text is here.","More text here also"]
我做了什么:
import re
c="Text is here. TEST . More text here also"
s=re.split('[A-Z][A-Z\d] ',c)
t=[re.sub('[^A-Za-z0-9]',' ',i) for i in s]
但我仍然得到一些不需要的空間:
['Text is here ', ' More text here also']
有沒有更清潔和 Pythonic 的生成方式t?
uj5u.com熱心網友回復:
>>> re.split('\s*[A-Z]{2,}[\s\.]*', c)
['Text is here.', 'More text here also']
空格(可選)后跟至少兩個大寫字符,后跟空格或點(可選)。
uj5u.com熱心網友回復:
這行得通,但它不是那么優雅。
c="Text is here. TEST . More text here also"
In [20]: [i.strip().replace('. ','') for i in c.split('TEST')]
Out[20]: ['Text is here.', 'More text here also']
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/475185.html
上一篇:正則運算式匹配字串中的多個數字
