简体   繁体   English

查找字符串中的最后一个元音

[英]Find the last vowel in a string

I cant seem to find the proper way to search a string for the last vowel, and store any unique consonants after that last vowel. 我似乎找不到正确的方法来搜索最后一个元音的字符串,并在最后一个元音之后存储任何唯一的辅音。 I have it set up like this so far. 到目前为止,我已经像这样设置了。

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:])

I like COLDSPEED's approach, but for completeness, I will suggest a regex based solution: 我喜欢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

See the docs on python regular expression syntax . 请参阅有关python正则表达式语法文档 Further processing is also needed for the uniqueness part ;) 唯一性部分还需要进一步处理;)

You can reverse your string, and use itertools.takewhile to take everything until the "last" (now the first after reversal) vowel: 您可以反转字符串,并使用itertools.takewhile取整,直到“最后”(现在是反转后的第一个)元音:

from itertools import takewhile

out = ''.join(takewhile(lambda x: x not in set('aeiou'), string[::-1]))[::-1]
print(out)
'ng'

If there are no vowels, the entire string is returned. 如果没有元音,则返回整个字符串。 Another thing to note is that, you should convert your input string to lower case using a str.lower call, otherwise you risk not counting uppercase vowels. 还要注意的另一件事是,您应该使用str.lower调用将输入字符串转换为小写,否则您将冒不计算大写元音的风险。


If you want unique consonants only (without any repetition), a further step is needed: 如果仅需要唯一辅音(不重复),则需要采取进一步的步骤:

from collections import OrderedDict
out = ''.join(OrderedDict.fromkeys(out).keys())

Here, the OrderedDict lets us keep order while eliminating duplicates, since, the keys must be unique in any dictionary. 在这里, OrderedDict让我们在消除重复的同时保持顺序,因为键在任何字典中都必须是唯一的。

Alternatively, if you want consonants that only appear once, use: 或者,如果您希望辅音出现一次,请使用:

from collections import Counter

c = Counter(out)
out = ''.join(x for x in out if c[x] == 1)

You can simply write a function for that: 您可以简单地为此编写一个函数:

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')

For example: 例如:

>>> func('asjhdskfdsbfkdes')
('e', 14, {'s'})

>>> func('asjhdskfdsbfkds')
('a', 0, {'b', 'd', 'f', 'h', 'j', 'k', 's'})

It returns the last vowel, the index of the vowel and all unique not-vowels after the last vowel. 它返回最后一个元音,该元音的索引以及最后一个元音之后的所有唯一非元音。

In case the vowels should be ordered you need to use an ordered container instead of the set, for example a list (could be much slower) or collections.OrderedDict (more memory expensive but faster than the list). 如果要订购元音,则需要使用有序容器而不是集合,例如list (可能会慢很多)或collections.OrderedDict (内存更大,但比列表快)。

You can just reverse your string and loop over each letter until you encounter the first vowel: 您可以反转字符串并循环遍历每个字母,直到遇到第一个元音为止:

for i, letter in enumerate(reversed(word)):
    if letter in VOWELS:
        break
print(word[-i:])

last_vowel will return the last vowel in the word last_vowel将返回单词中的最后一个元音

last_index will give you the last index of this vowel in the input last_index将为您提供该元音在输入中的最后一个索引

Python 2.7 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 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM