消除在python使用正则表达式单词之间的空格

问题描述:

我想消除中含有一句多的话消除在python使用正则表达式单词之间的空格

2字与字之间的空白

我的代码如下所示:

import re 
sentence = "open app store" 
pattern = re.compile(r'\b([a-z]) (?=[a-z]\b)', re.I) 
sentence = re.sub(pattern, r'\g<1>', sentence) 
print(sentence) 

输出:

open app store 

我想删除应用程序和商店之间的空白区域。我想要这样的输出“打开appstore”。

请注意,app不会总是拿出store,app可以与其他一些词后来,例如, app maker

+6

你应用了什么规则,以便它变成“开放的appstore”而不是“openapp store”? –

+0

您想在字符串中的最后一个单词之前删除空格吗?见https://ideone.com/uYTWnZ –

+0

你的规则是什么?如果'app store'可能会出现在字符串的任何位置,那么您想如何匹配它? –

让我们来看看your pattern:一个字边界一致时,捕捉任何ASCII字母为1组,则匹配的空间,然后声称有一个单一的ASCII字母后面有一个单词边界。因此,它可以匹配a b,My a b string,但不匹配app store

现在,它似乎是你的app值是静态的,之后你想匹配一个或多个空格,只有当app之后有另一个单词时。你可以遵循两个策略。

您可以匹配app后跟用空格(S)和一个字母,然后删除空格(见this Python demo):

re.sub(r"\b(app)\s+([a-z])", r"\1\2", sentence, flags=re.I) 

(也见the regex demo),或者你可以使用已知单词遵循app只有消除它们之间的空隙:

re.sub(r"\b(app)\s+(store|maker|market|etc)", r"\1\2", sentence, flags=re.I) 

another regex demoanother Python demo

+1

非常感谢。它为我工作。 – Sonal

试试这个:

import re 
sentence = "This is test" 
pattern = re.compile(r'(.*)\b\s+(?=[a-z])', re.I | re.S) 
sentence = re.sub(pattern, r'\1', sentence) 
print(sentence) 

输出:此istest

希望它为你工作。

+1

“应用商店”并不总是句子的最后一个词。它可以在任何地方在句子中。 – Sonal

这可以为你工作。

>>> import re 
>>> sentence = "this is an open app store and this is another open app store." 
>>> pattern = re.compile(r'app[\s]store') 
>>> replacement = 'appstore' 
>>> result = re.sub(pattern, replacement, sentence) 
>>> result 
'this is an open appstore and this is another open appstore.' 

编辑:您可以使用此函数来消除任何两个单词之间的空格。

import re 

def remove_spaces(text, word_one, word_two): 
    """ Return text after removing whitespace(s) between two specific words. 

    >>> remove_spaces("an app store app maker app store", "app", "store") 
    'an appstore, app maker, appstore' 
    """ 

    pattern = re.compile(r'{}[\s]*{}'.format(word_one, word_two)) # zero or more spaces 
    replacement = word_one + word_two 
    result = re.sub(pattern, replacement, text) 

    return result 
+1

“应用程序”不会总是拿出“商店”。 “应用程序”可以附带其他扩展名。例如“应用程序制造商”。你能帮我相应吗? – Sonal

+0

@Sonal,它仍然有效。看起来你没有用“app”之后的另一个词来测试它 – srig