[英]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.