![](/img/trans.png)
[英]Python Multiple regex Patterns string reassignment using re.sub
[英]Python (2.7) - Replacing multiple patterns in a string using re
我正在嘗試一種更優雅的方法,使用re
替換給定字符串中的多個模式,這與一個小問題有關,即從給定字符串中刪除由兩個以上空格組成的所有子字符串,以及所有包含字母的子字符串在沒有空格的時間段后開始。 所以這句話
'This is a strange sentence. There are too many spaces.And.Some periods are not. placed properly.'
應該更正為:
'This is a strange sentence. There are too many spaces. And. Some periods are not. placed properly.'
下面的我的解決方案似乎有些混亂。 我想知道是否有更好的方法,例如單行正則表達式。
def correct( astring ):
import re
bstring = re.sub( r' +', ' ', astring )
letters = [frag.strip( '.' ) for frag in re.findall( r'\.\w', bstring )]
for letter in letters:
bstring = re.sub( r'\.{}'.format( letter ), '. {}'.format( letter ), bstring )
return bstring
s = 'This is a strange sentence. There are too many spaces.And.Some periods are not. placed properly.'
print(re.sub("\s+"," ",s).replace(".",". ").rstrip())
This is a strange sentence. There are too many spaces. And. Some periods are not. placed properly.
您可以使用如下的re.sub
函數。 除最后一個點外,這將在該點旁邊恰好添加兩個空格,並且還會用一個空格替換一個或多個空格(除了后一個點之外)。
>>> s = 'This is a strange sentence. There are too many spaces.And.Some periods are not. placed properly.'
>>> re.sub(r'(?<!\.)\s+', ' ' ,re.sub(r'\.\s*(?!$)', r'. ', s))
'This is a strange sentence. There are too many spaces. And. Some periods are not. placed properly.'
要么
>>> re.sub(r'\.\s*(?!$)', r'. ', re.sub(r'\s+', ' ', s))
'This is a strange sentence. There are too many spaces. And. Some periods are not. placed properly.'
不使用任何RegEX的方法
>>> ' '.join(s.split()).replace('.','. ')[:-1]
'This is a strange sentence. There are too many spaces. And. Some periods are not. placed properly.'
什么是純正則表達式? 像這樣?
>>> import re
>>> s = 'This is a strange sentence. There are too many spaces.And.Some periods are not. placed properly.'
>>> re.sub('\s+$', '', re.sub('\s+', ' ', re.sub('\.', '. ', s)))
'This is a strange sentence. There are too many spaces. And. Some periods are not. placed properly.'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.