除去元音,除非它是单词的开头

2024-07-08 07:26:30 发布

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

我试图删除字符串中元音的出现,除非它们是单词的开头。例如,"The boy is about to win"这样的输入应该输出Th by is abt t wn。任何帮助都将不胜感激!在

def short(s):
vowels = ('a', 'e', 'i', 'o', 'u')
noVowel= s
toLower = s.lower()
for i in toLower.split():
    if i[0] not in vowels:
        noVowel = noVowel.replace(i, '')        
return noVowel

Tags: theto字符串inbyis单词win
3条回答

一种方法是使用正则表达式替换前面没有单词边界的元音。另外,如果您的代码应该处理带有各种标点符号的任意文本,那么您可能需要考虑一些更有趣的测试用例。在

import re
s = "The boy is about to win (or draw). Give him a trophy to boost his self-esteem."
rgx = re.compile(r'\B[aeiou]', re.IGNORECASE)
print rgx.sub('', s)  # Th by is abt t wn (or drw). Gv hm a trphy t bst hs slf-estm.

可以对字符串的其余部分使用regex(忽略第一个字符):

import re
s = 'The boy is about to win'
s = s[0] + re.sub(r'[aeiou]', '', s[1:])
print s # Th by s bt t wn

尝试:

>>> s = "The boy is about to win"
>>> ''.join(c for i, c in enumerate(s) if not (c in 'aeiou' and i>1 and s[i-1].isalpha()))
'Th by is abt t wn'

工作原理:

如果发电机:

^{pr2}$

发电机的关键部件是:

if not (c in 'aeiou' and i>1 and s[i-1].isalpha())

这意味着s中的所有字母都包括在内,除非它们不是(a)在s开头的元音,也不是(b)前面有一个非字母,这也意味着它们在单词的开头。在

重写为for循环

def short(s):
    new = ''
    prior = ''
    for c in s:
        if not (c in 'aeiou' and prior.isalpha()):
            new += c
        prior = c
    return new

相关问题 更多 >

    热门问题