2016-10-22 65 views
3

我想从字符串中删除首字母缩略词中的句点,但我也希望o定期(例如在句子结尾)保留句号。正则表达式来删除首字母缩略词中的句点?

所以下面的句子:

"The C.I.A. is a department in the U.S. Government." 

应该成为

"The CIA is a department in the US Government." 

有没有干净的方式来做到这一点使用Python?到目前为止,我有两个步骤:

words = "The C.I.A. is a department in the U.S. Government." 
words = re.sub(r'([A-Z].[A-Z.]*)\.', r'\1', words) 
print words 
# The C.I.A is a department in the U.S Government.  
words = re.sub(r'\.([A-Z])', r'\1', words) 
print words 
# The CIA is a department in the US Government. 
+4

可以有任何单字母缩写吗? –

+0

'etc.'呢?如果你只关心大写单个字母后跟一个点,你可以使用're.sub(r'\ b([AZ])\。',r'\ 1',words)',但这不是一般的解。 –

+0

归结到这个问题*“你怎么知道什么是一个缩略语而不是一个句子?”*一旦你有了答案,那么你就可以开始构建一个正则表达式。 – zvone

回答

8

大概是这样吗?

>>> re.sub(r'(?<!\w)([A-Z])\.', r'\1', s) 
'The CIA is a department in the US Government.' 

更换已经由一个大写的单个字母开头所提供的单个字母没有立即在\w字符集前面任何单独点。后面的标准由负反序断言 - (?<!\w)执行。

+1

很想知道OP是否仍然在寻找像'etc.'这样的东西。否则,这很好。 – idjaw

+0

@idjaw啊,是的,很好的观察。他们需要证实这一点。 –

+0

您可能还想要解释代码。实际上,在句子中'I'也是失败的。 –

相关问题