python - 删除 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(大写和小写)。
我的解决方案
伪代码
- 分解句子
- 对于每个单词,找到最后一个元音的索引
- 然后将其删除并制作新的“单词”
- 连接所有单词
代码
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()
功能吗?具体来说,如果一个人已经可以删除最后一个元音而不必先找到相应的索引。
解决方案
这可以通过正则表达式替换来更容易地实现,该替换删除后面跟着零个或多个辅音直到单词边界的元音:
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.
推荐阅读
- bazel - 使用 bazel genrule 添加外部依赖项失败并出现错误“没有输出的 Genrules 没有意义”
- ios - 原生到 React Native 调用
- spring-boot - 在 EC2 上启用 SSL 是否必须使用 Amazon Route 54?
- python - 从熊猫的字符串日期时间列中提取日期
- flutter - 在颤动中调整容器大小以精确到屏幕大小的一半
- javascript - 重置用于打印的 javascript 结果
- javascript - Visjs/React:动态构建数据集
- java - 错误:java:错误:无效的源版本:13 使用 JDK12 和 IntelliJ
- php - 我的代码出现数据库有什么问题?
- swift - MKPointAnnotation 到 MKMapItem