在一个单词中找到连续的辅音

2024-05-18 23:44:40 发布

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

我需要能显示单词中连续辅音的代码。例如,对于"concertation",我需要获得["c","nc","rt","t","n"]。在

这是我的代码:

def SuiteConsonnes(mot):
    consonnes=[]
    for x in mot:
        if x in "bcdfghjklmnprstvyz":
           consonnes += x + ''
    return consonnes

我设法找到了辅音,但我不知道如何连续找到它们。谁能告诉我我需要做什么吗?在


Tags: 代码inforreturnifdef单词nc
3条回答

您可以使用正则表达式,在^{} module中实现

更好的解决方案

>>> re.findall(r'[bcdfghjklmnpqrstvwxyz]+', "concertation", re.IGNORECASE)
['c', 'nc', 'rt', 't', 'n']
  • [bcdfghjklmnprstvyz]+匹配字符类中一个或多个字符的任意序列

  • re.IGNORECASE对字符启用区分大小写匹配。那就是

    >>> re.findall(r'[bcdfghjklmnpqrstvwxyz]+', "CONCERTATION", re.IGNORECASE)
    ['C', 'NC', 'RT', 'T', 'N']
    

另一个解决方案

>>> import re
>>> re.findall(r'[^aeiou]+', "concertation",)
['c', 'nc', 'rt', 't', 'n']
  • [^aeiou]字符类被否定。匹配除此字符类中的字符以外的任何字符。简而言之就是匹配字符串中的辅音

  • +量子化器+匹配字符串中出现的一个或多个模式

注意这也会在解决方案中找到非字母的相邻字符。因为字符类是除了元音以外的任何东西

示例

>>> re.findall(r'[^aeiou]+', "123concertation",)
['123c', 'nc', 'rt', 't', 'n']

如果您确定输入始终包含字母表,则此解决方案是可以的


 re.findall(pattern, string, flags=0)

    Return all non-overlapping matches of pattern in string, as a list of strings. 
    The string is scanned left-to-right, and matches are returned in the order found. 

如果你想知道结果是如何得到的

re.findall(r'[bcdfghjklmnpqrstvwxyz]+', "concertation")

concertation
|
c

concertation
 |
 # o is not present in the character class. Matching ends here. Adds match, 'c' to ouput list


concertation
  |
  n

concertation
   |
   c


concertation
    |
     # Match ends again. Adds match 'nc' to list 
     # And so on

可以使用正则表达式和re模块的split函数来完成此操作:

>>> import re
>>> re.split(r"[aeiou]+", "concertation", flags=re.I)
['c', 'nc', 'rt', 't', 'n']

此方法在匹配一个或多个连续元音时拆分字符串。在

解释正则表达式"[aeiou]+":这里元音被收集到一个类[aeiou],而{}表示该类中任何字符的一个或多个匹配。因此,字符串"concertation"oea和{}处拆分。在

re.I标志意味着将忽略字母的大小写,从而有效地使字符类等于[aAeEiIoOuU]。在

编辑:需要记住的一点是,这种方法隐含地假设单词只包含元音和辅音。数字和标点符号将被视为非元音/辅音。要只匹配连续的辅音,请使用re.findall与character类中列出的辅音(如其他答案中所述)。在

键入所有辅音的一个有用的快捷方式是使用第三方^{}模块而不是{}。在

本模块支持set运算,因此包含辅音的字符类可以整洁地写成整个字母表减去元音:

^{pr2}$

其中[a-z]是整个字母表,--是集差,而{}是元音。在

如果您想要一个非regex解决方案,itertools.groupby在这里可以很好地工作,就像这样

>>> from itertools import groupby
>>> is_vowel = lambda char: char in "aAeEiIoOuU"
>>> def suiteConsonnes(in_str):
...     return ["".join(g) for v, g in groupby(in_str, key=is_vowel) if not v]
... 
>>> suiteConsonnes("concertation")
['c', 'nc', 'rt', 't', 'n']

相关问题 更多 >

    热门问题