【问题标题】:eliminate white spaces between words using regex in python在python中使用正则表达式消除单词之间的空格
【发布时间】:2017-10-18 15:46:40
【问题描述】:

我想消除包含许多单词的句子中两个单词之间的空格

我的代码如下所示:

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

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

请注意,app 并不总是会出现 storeapp 可以在其后出现其他单词,例如app maker.

【问题讨论】:

  • 你应用了什么规则使它变成open appstore而不是openapp store
  • 您要删除字符串中最后一个单词之前的空格吗?见ideone.com/uYTWnZ
  • 你的规则是什么?如果app store 可能出现在字符串中的任何位置,你想如何匹配它?
  • @WiktorStribiżew:app store 可以出现在句子的任何地方。我想在句子中匹配app store 字符串并将其替换为appstore
  • 查看我的回答,解释问题和 2 个解决方案。

标签: python regex


【解决方案1】:

让我们看一下your pattern:它匹配一个单词边界,然后将任何 ASCII 字母捕获到第 1 组,然后匹配一个空格,然后断言有一个 ASCII 字母后跟一个单词边界。所以,它可以匹配My a b string 中的a b,但不能匹配app store

现在,您的 app 值似乎是静态的,只有在 app 后面还有另一个单词时,您才想匹配 1 个或多个空格。您可以遵循两种策略。

您可以匹配app,其后跟空格和一个字母,然后删除空格(请参阅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

【讨论】:

    【解决方案2】:

    这可能对你有用。

    >>> 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
    

    【讨论】:

    • "app" 不会总是出现"store"。 “app”可以与其他一些扩展一起出现。例如“应用程序制造商”。你能相应地帮助我吗?
    • @Sonal,它仍然有效。看来你没有在“app”之后用不同的词测试它
    【解决方案3】:

    试试这个:

    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)
    

    输出:这是测试

    希望它对你有用。

    【讨论】:

    • "app store" 并不总是最后一句话。它可以出现在句子的任何地方。
    猜你喜欢
    • 2017-12-24
    • 1970-01-01
    • 2013-03-06
    • 2021-01-06
    • 2018-08-29
    • 1970-01-01
    • 2021-06-10
    • 2014-09-04
    相关资源
    最近更新 更多