gpt4 book ai didi

python - Regex Python - 如何获取不连续出现的次数?

转载 作者:太空宇宙 更新时间:2023-11-03 20:39:27 27 4
gpt4 key购买 nike

这是我的代码,我想获取基于此模式的组合数量:x - y - x ,例如:"UBU" , "ANA", "INI"

    import re 

pattern = r"(?P<name>[a-z]).(?P=name)"

print(len(re.findall(pattern, "hello"))) # should return 0 : OK

print(len(re.findall(pattern, "mirror"))) # should return 1 because there is "ror" : OK

print(len(re.findall(pattern, "irir"))) #should return 2 because there are "iri" and "rir" : return just 1

当部分组合叠瓦式插入另一个组合时,就像“iri”中“rir”的前两个字母一样,它不起作用。

您知道如何获得这些组合的正确数量(对于第三个示例)吗?预先非常感谢您

最佳答案

def pattern_counter(word):
return sum([1 for index, letter in enumerate(word[:(len(word)-2)]) if letter == word[index+2]])

word1 = "hello"
word2 = "mirror"
word3 = "irir"

print(pattern_counter(word1)) # prints 0
print(pattern_counter(word2)) # prints 1
print(pattern_counter(word3)) # prints 2

关于python - Regex Python - 如何获取不连续出现的次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56947637/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com