Python:删除word中连续出现N次以上的字母

2024-09-30 01:19:58 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一句话:

sentence = "Eveeery mondayyy I waaake upp"

我想创建一个函数,删除一个单词中连续出现超过N次的所有字母。你知道吗

所以,如果我说:N=2 结果应该是:

result = Eveery mondayy I waake upp

我怎样才能有效地做到这一点?你知道吗


Tags: 函数字母result单词sentenceuppwaaakewaake
3条回答

re.sub()解决方案:

import re

def remove_continued_char(s, n):
    pat = re.compile(r'([a-z])(\1{' + str(n) + '})')
    return pat.sub('\\2', s)

sentence = 'Eveeery mondayyy I waaake upp'
print(remove_continued_char(sentence, 2))

输出:

Eveery mondayy I waake upp

  • [a-z]-只匹配字母字符(字母)
  • \1-对第一个捕获组的反向引用,即([a-z])
  • \\2-指向第二个捕获的(带圆括号的)组值

你必须反复阅读这个句子的字母,而柯平跟踪上一个字母,以及它被看到了多少次。你知道吗

def del_n(n, s):
    so_far = 1
    previous = s[0]
    res = [s[0]]

    for idx, c in enumerate(s[1:]):
        if c == previous:
            so_far += 1
            if so_far >= n+1:
                continue
        else:
            previous = c
            so_far = 1
        res.append(c)
    return ''.join(res)


sentence = "Eveeery mondayyy I waaake upp"
del_n(2, sentence)

输出:

'Eveery mondayy I waake upp'

给你一个好的开始: 只需发布一个示例,它可能会帮助您:

import re
regex = r"(.)\1+"
test_str = "sentence = Eveeery mondayyy I waaake upp"
# use \\1\\1 if you need to replace with two characters and so on 
subst = "\\1"
# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0)
if result:
    print (result)

输出:

>>>Every monday I wake up

希望这有帮助

相关问题 更多 >

    热门问题