首页 > 解决方案 > 删除 Python 中的最后一个元音

问题描述

我有以下问题,我想知道是否有更快更干净的removeLastChar()功能实现。具体来说,如果一个人已经可以删除最后一个元音而不必先找到相应的索引。

问题

编写一个函数,删除句子中每个单词的最后一个元音。

例子:

removeLastVowel("Those who dare to fail miserably can achieve greatly.")

“那些谁敢悲惨地完成了。”

removeLastVowel("Love is a serious mental disease.")

“爱的严重精神病”

removeLastVowel("Get busy living or get busy dying.")

“gt bsy livng r gt bsy dyng”

注意:元音是:a、e、i、o、u(大写和小写)。

我的解决方案

伪代码

  1. 分解句子
  2. 对于每个单词,找到最后一个元音的索引
  3. 然后将其删除并制作新的“单词”
  4. 连接所有单词

代码

def findLastVowel(word):
    set_of_vowels = {'a','e','i','o','u'}
    last_vowel=''
    for letter in reversed(word):
        if letter in set_of_vowels:
            last_vowel = letter
            break
    return last_vowel
 
def removeLastChar(input_str,char_to_remove):
    index = input_str.find(char_to_remove)
    indices = []
    tmp_str = input_str
    if index != -1:
        while index != -1:
            indices.append(index)
            substr1 = tmp_str[:index]
            substr2 = tmp_str[index+1:]
            tmp_str = substr1+"#"+substr2
            index = tmp_str.find(char_to_remove) 
        
        index = indices[-1]
        substr1 = input_str[:index]
        substr2 = input_str[index+1:]
        return (substr1+substr2)
    else:
        return (input_str)

def removeLastVowel(sentence):
    decomposed_sentence = sentence.split()
    out = []
    for word in decomposed_sentence:
        out.append(removeLastChar(word,findLastVowel(word)))
    print(" ".join(out))


#MAIN
removeLastVowel("Those who dare to fail miserably can achieve greatly.")
removeLastVowel("Love is a serious mental disease.")
removeLastVowel("Get busy living or get busy dying.")

输出

Thos wh dar t fal miserbly cn achiev gretly.
Lov s  serios mentl diseas.
Gt bsy livng r gt bsy dyng.

问题

您能建议更好地实现该 removeLastChar()功能吗?具体来说,如果一个人已经可以删除最后一个元音而不必先找到相应的索引。

标签: pythonstring

解决方案


这可以通过正则表达式替换来更容易地实现,该替换删除后面跟着零个或多个辅音直到单词边界的元音:

import re

def removeLastVowel(s):
    return re.sub(r'[aeiou](?=[^\Waeiou]*\b)', '', s, flags=re.I)

以便:

removeLastVowel("Those who dare to fail miserably can achieve greatly.")

返回:

Thos wh dar t fal miserbly cn achiev gretly.

推荐阅读