[英]Find the last vowel in a string
我似乎找不到正确的方法来搜索最后一个元音的字符串,并在最后一个元音之后存储任何唯一的辅音。 到目前为止,我已经像这样设置了。
word = input('Input a word: ')
wordlow = word.lower()
VOWELS = 'aeiou'
last_vowel_index = 0
for i, ch in enumerate(wordlow):
if ch == VOWELS:
last_vowel_index += i
print(wordlow[last_vowel_index + 1:])
我喜欢COLDSPEED的方法,但是为了完整起见 ,我将建议一个基于正则表达式的解决方案:
import re
s = 'sjdhgdfgukgdk'
re.search(r'([^AEIOUaeiou]*)$', s).group(1)
# 'kgdk'
# '[^AEIOUaeiou]' matches a non-vowel (^ being the negation)
# 'X*' matches 0 or more X
# '$' matches the end of the string
# () marks a group, group(1) returns the first such group
请参阅有关python正则表达式语法的文档 。 唯一性部分还需要进一步处理;)
您可以反转字符串,并使用itertools.takewhile
取整,直到“最后”(现在是反转后的第一个)元音:
from itertools import takewhile
out = ''.join(takewhile(lambda x: x not in set('aeiou'), string[::-1]))[::-1]
print(out)
'ng'
如果没有元音,则返回整个字符串。 还要注意的另一件事是,您应该使用str.lower
调用将输入字符串转换为小写,否则您将冒不计算大写元音的风险。
如果仅需要唯一辅音(不重复),则需要采取进一步的步骤:
from collections import OrderedDict
out = ''.join(OrderedDict.fromkeys(out).keys())
在这里, OrderedDict
让我们在消除重复的同时保持顺序,因为键在任何字典中都必须是唯一的。
或者,如果您希望辅音仅出现一次,请使用:
from collections import Counter
c = Counter(out)
out = ''.join(x for x in out if c[x] == 1)
您可以简单地为此编写一个函数:
def func(astr):
vowels = set('aeiouAEIOU')
# Container for all unique not-vowels after the last vowel
unique_notvowels = set()
# iterate over reversed string that way you don't need to reset the index
# every time a vowel is encountered.
for idx, item in enumerate(astr[::-1], 1):
if item in vowels:
# return the vowel, the index of the vowel and the container
return astr[-idx], len(astr)-idx, unique_notvowels
unique_notvowels.add(item)
# In case no vowel is found this will raise an Exception. You might want/need
# a different behavior...
raise ValueError('no vowels found')
例如:
>>> func('asjhdskfdsbfkdes')
('e', 14, {'s'})
>>> func('asjhdskfdsbfkds')
('a', 0, {'b', 'd', 'f', 'h', 'j', 'k', 's'})
它返回最后一个元音,该元音的索引以及最后一个元音之后的所有唯一非元音。
如果要订购元音,则需要使用有序容器而不是集合,例如list
(可能会慢很多)或collections.OrderedDict
(内存更大,但比列表快)。
您可以反转字符串并循环遍历每个字母,直到遇到第一个元音为止:
for i, letter in enumerate(reversed(word)):
if letter in VOWELS:
break
print(word[-i:])
last_vowel
将返回单词中的最后一个元音
last_index
将为您提供该元音在输入中的最后一个索引
Python 2.7
input = raw_input('Input a word: ').lower()
last_vowel = [a for a in input if a in "aeiou"][-1]
last_index = input.rfind(last_vowel)
print(last_vowel)
print(last_index)
Python 3.x
input = input('Input a word: ').lower()
last_vowel = [a for a in input if a in "aeiou"][-1]
last_index = input.rfind(last_vowel)
print(last_vowel)
print(last_index)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.