Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python如何消除3个或更多后续字母_Python - Fatal编程技术网

Python如何消除3个或更多后续字母

Python如何消除3个或更多后续字母,python,Python,我试着把那些连续字母超过3个的单词从“真”替换为“真” pattern = re.compile(r"(.)\1\1{2,}", re.DOTALL) return pattern.sub(r"\1\1\1", text) 我无法让它工作,有人能帮忙吗?您的解决方案实际上似乎工作正常: >>重新导入 >>>a='fooooobaaar' >>>reg=re.compile(r“()\1\1{2,}”) >>>注册子(r'\1\1',a) “福巴尔” 但是根据注释,您想用xyyx替换xyyx,

我试着把那些连续字母超过3个的单词从“真”替换为“真”

pattern = re.compile(r"(.)\1\1{2,}", re.DOTALL)
return pattern.sub(r"\1\1\1", text)

我无法让它工作,有人能帮忙吗?

您的解决方案实际上似乎工作正常:

>>重新导入
>>>a='fooooobaaar'
>>>reg=re.compile(r“()\1\1{2,}”)
>>>注册子(r'\1\1',a)
“福巴尔”
但是根据注释,您想用
xyyx
替换
xyyx
,但您至少为其中4个指定了regexp,因此只有
xyyyyx
被替换。。。只需更改此行:

>>reg=re.compile(r“()\1{2,}”)
>>>注册子(r'\1\1',实际上是“fooo baaar”)
“实际上是福巴尔”

我建议在不需要正则表达式时不要使用它们。这项任务可以很容易地完成,而不需要线性时间和恒定空间复杂性(不确定正则表达式)

def过滤器重复次数(文本,最大重复次数=0):
最后一个字符=无
重复计数=0
对于文本中的字符:
如果字符==最后一个字符:
重复计数+=1
其他:
最后一个字符=字符
重复计数=0

如果您的解决方案与Python3.2兼容,那么问题出在哪里?我得到一个字符串是yummmy,它不能替代yummmy。我使用Python2.7,它会影响吗?
def filter_repetitions(text, max_repetitions=0):
    last_character = None
    repetition_count = 0
    for character in text:
        if character == last_character:
            repetition_count += 1
        else:
            last_character = character
            repetition_count = 0
        if repetition_count <= max_repetitions:
            yield character

print ''.join(filter_repetitions("fooo baaaar actuallly", 1))