【问题标题】:Remove duplicated letters except in abbreviations删除重复的字母,缩写除外
【发布时间】:2020-11-18 20:08:44
【问题描述】:

只要有更多字母,我想从字符串中删除重复的字母。例如,考虑以下列表:

aaa --> it is untouched because all are the same letters
aa  --> it is untouched because all are the same letters
a   --> not touched, just one letter
broom --> brom
school --> schol
boo --> should be bo
gool --> gol
ooow  --> should be ow

我使用以下正则表达式来消除重复项,如下所示:

(?<=[a-zA-Z])([a-zA-Z])\1+(?=[a-zA-Z])

但是,这在字符串boo 中失败,该字符串保留为原始boo,而不是删除双o。 oow 也会发生同样的情况,它不会简化为 ow

你知道为什么boo 不被正则表达式占用吗?

【问题讨论】:

  • gogolgogoolgoogolgoogool 的输出应该是什么?
  • 应该都是果戈理。重复项仅适用于一个字母

标签: python python-3.x regex regex-lookarounds


【解决方案1】:

您可以将由相同字符组成的整个单词匹配并捕获到一个捕获组中,然后在所有其他上下文中匹配重复的连续字母,并相应地替换:

import re
text = "aaa, aa, a,broom, school...boo, gool, ooow."
print( re.sub(r'\b(([a-zA-Z])\2+)\b|([a-zA-Z])\3+', r'\1\3', text) )
# => aaa, aa, a,brom, schol...bo, gol, ow.

请参阅Python demoregex demo

正则表达式详细信息

  • \b - 单词边界
  • (([a-zA-Z])\2+) - 第 1 组:一个 ASCII 字母(捕获到第 2 组),然后出现一个或多个相同字母
  • \b - 单词边界
  • | - 或
  • ([a-zA-Z]) - 第 3 组:捕获到第 3 组的 ASCII 字母
  • \3+ - 在第 3 组中捕获的字母出现一次或多次。

替换是第 1 组和第 3 组值的串联。

要匹配任何 Unicode 字母,请将 [a-zA-Z] 替换为 [^\W\d_]

【讨论】:

    【解决方案2】:

    您的正则表达式不匹配 boo,因为它会搜索前后至少有一个不同字符的重复项。

    一种可能性是制作一个更简单的正则表达式来捕获所有重复项,然后如果结果是一个字符则恢复

    def remove_duplicate(string):
        new_string = re.sub(r'([a-zA-Z])\1+', r'\1', string)
        return new_string if len(new_string) > 1 else string
    

    这是一个没有正则表达式的可能解决方案。它更快,但它也会删除重复的空格和标点符号。不仅仅是字母。

    def remove_duplicate(string):
        new_string = ''
        last_c = None
        for c in string:
            if c == last_c:
                continue
            else:
                new_string += c
                last_c = c
        if len(new_string) > 1:
            return new_string
        else:
            return string
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-03
      • 2023-03-21
      • 2022-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-11
      • 2021-06-05
      相关资源
      最近更新 更多