在python中查找由重复字符组成的单词

2024-04-20 12:03:04 发布

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

免责声明:我发现很多类似的问题,但不是具体的问题。一旦有人回答,我会删除它。你知道吗

我需要找到所有的蒙面词,比如:

AAAAA likes apples, but BBBBB likes bananas. Their phone numbers are ffffr and ggggh.

图案至少是重复字符的三倍。你知道吗

当我使用:

import re

p = re.compile(r'[a-z]{3,}, re.IGNORECASE)
m = p.findall('AAAAA likes apples, but BBBBB likes bananas. Their phone numbers are ffffr and ggggh.')

我只得到所有单词(包含3个以上字符)。你知道吗

理想情况下,我应该只得到:

m = ['AAAAA', 'BBBBB', 'ffffr', 'ggggh']

我应该如何改变愤怒的规则来只捕捉那些?你知道吗

谢谢!你知道吗


Tags: andrephone字符arebutlikesnumbers
3条回答

您可以使用正则表达式,但我建议使用其他方法,即:

txt = 'AAAAA likes apples, but BBBBB likes bananas. Their phone numbers are ffffr and ggggh.'
words = txt.split(' ')
found = [i for i in words if len(set(i[:3].lower()))==1]
print(found) # ['AAAAA', 'BBBBB', 'ffffr', 'ggggh.']

请注意,现在found与所需的输出不完全相同,因为最后一个元素中有.,但我们可以通过以下方式轻松删除任何尾随标点:

import string
clear_found = [i.rstrip(string.punctuation) for i in found]
print(clear_found) # ['AAAAA', 'BBBBB', 'ffffr', 'ggggh']

我的方法说明:我得到单词的前3个字符,将它们全部小写,然后使用set检查是否只有一个字母(字符)。或者您可以使用.upperstr方法。如果您认为基于regex的解决方案更适合您的用例,请随意使用它,但请记住,对于某些问题,存在非regex解决方案的可能性。你知道吗

在这里,如果我们想捕获一个单词,我们将使用一个单词边界,并使用类似于以下表达式的反向引用:

\b([a-z])\1\1\1.+?\b

Demo

测试

# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"\b([a-z])\1\1\1.+?\b"

test_str = "AAAAA likes apples, but BBBBB likes bananas. Their phone numbers are ffffr and ggggh."

matches = re.finditer(regex, test_str, re.MULTILINE | re.IGNORECASE)

for matchNum, match in enumerate(matches, start=1):

    print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))

    for groupNum in range(0, len(match.groups())):
        groupNum = groupNum + 1

        print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.

正则表达式电路

jex.im可视化正则表达式:

enter image description here

您当前的正则表达式只检查三个或更多的[a-z],而不检查重复的。为了检查一个字母是否重复,您需要稍后再capturebackreference检查它。使用re.IGNORECASE

\b\w*?([a-z])\1\1\w*\b

See demo at regex101

这将匹配至少3个被任意数量的\w字字符包围的重复[a-z]。你知道吗

相关问题 更多 >