如何在Python中从字符串中删除辅音?

对于此问题,使用正则表达式是最简单的。您可以使用“ |”分隔多个字符 并使用re.sub(chars_to_replace,string_to_replace_with,str)。例如:

>>> import re
>>> consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z']
>>> re.sub('|'.join(consonants), "", "Hello people", flags=re.IGNORECASE)
"eo eoe"

注意:您也可以使用[]创建要在正则表达式中替换的字符组。

如果只想保留元音并删除所有其他字符,则可以使用更简单的版本。请注意,它也会删除空格,数字等。例如,

>>> import re
>>> re.sub('[^aeiou]', "", "Hello people", flags=re.IGNORECASE)
"eoeoe"

您还可以如下过滤辅音:

>>> consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z']
>>> s = "Hello people"
>>> ''.join(c for c in s if c.lower() not in consonants)
'eo eoe'