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

oez*_*lem 13 python string

我需要能够向我显示一个单词中连续辅音的代码.例如,因为"concertation"我需要获得["c","nc","rt","t","n"].

这是我的代码:

def SuiteConsonnes(mot):
    consonnes=[]
    for x in mot:
        if x in "bcdfghjklmnprstvyz":
           consonnes += x + ''
    return consonnes
Run Code Online (Sandbox Code Playgroud)

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

nu1*_*73R 20

您可以使用在模块中实现的正则表达式re

好的解决方案

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

  • re.IGNORECASE启用字符敏感匹配的案例.那是

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

另一种方案

>>> import re
>>> re.findall(r'[^aeiou]+', "concertation",)
['c', 'nc', 'rt', 't', 'n']
Run Code Online (Sandbox Code Playgroud)
  • [^aeiou]否定的字符类.匹配此角色类中除此之外的任何字符.这就是字符串中的匹配组件

  • +quantfer +匹配字符串中模式的一个或多个出现

注意这也将在解决方案中找到非字母,相邻的字符.由于字符类是任何东西比其他元音

例

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

如果您确定输入始终包含字母表,那么此解决方案就可以了


 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. 
Run Code Online (Sandbox Code Playgroud)

如果您对如何获得结果感到好奇

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
Run Code Online (Sandbox Code Playgroud)


Ale*_*ley 11

你可以用正则表达式和re模块的split功能来做到这一点:

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

只要一个或多个连续元音匹配,此方法就会分割字符串.

解释正则表达式"[aeiou]+":这里元音已被收集到一个类中,[aeiou]而+表示可以匹配此类中任何一个或多个字符.因此,串"concertation"在分裂o,e,a和io.

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

编辑:要记住的一件事是,此方法隐含地假定该单词仅包含元音和辅音.数字和标点符号将被视为非元音/辅音.要仅匹配连续的辅音,而是使用re.findall字符类中列出的辅音(如其他答案中所述).

输入所有辅音的一个有用的捷径是使用第三方regex模块而不是re.

此模块支持set操作,因此包含辅音的字符类可以整齐地写为整个字母减去元音:

[[a-z]--[aeiou]] # equal to [bcdefghjklmnpqrstvwxyz]
Run Code Online (Sandbox Code Playgroud)

[a-z]整个字母表在哪里,--设置差异并且[aeiou]是元音.


the*_*eye 9

如果你想要一个非正则表达式解决方案,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']
Run Code Online (Sandbox Code Playgroud)