2017-09-25 65 views
2

我似乎找不到找到最後一個元音字符串的正確方法,並在最後一個元音後面存儲任何獨特的輔音。到目前爲止,我已經設置了它。查找字符串中的最後一個元音

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

爲什麼將_adding_'i'放到'last_vowel_index'上? – khelwood

+0

你是在討論if循環還是打印時?或者地獄,甚至兩個? – manoman181

+0

'last_vowel_index + = i' < - 這。我想不出任何理由。 – khelwood

回答

2

你可以扭轉你的字符串,並使用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) 
+0

@schwobaseggl嗯,沒有看到。現在認爲它應該沒問題。 –

+1

OP不清楚「獨特輔音」的含義。我的意思是在最後一個元音後僅出現1次的輔音,還是他只是想刪除重複的? –

+0

@DavidJenkins編輯。這些nitpicks很容易解決。 –

0

你可以簡單地寫一個函數爲:

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

它返回最後的元音,元音a的索引在最後一個元音之後找出所有獨特的非元音。

如果應該訂購元音,您需要使用有序容器而不是集合,例如list(可能要慢得多)或collections.OrderedDict(內存更貴,但比列表更快)。

-1

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

我喜歡COLDSPEED's approac小時,但爲了完整,我會建議一個基於正則表達式的解決方案:

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 

docs on python regular expression syntax。對於唯一性部分,還需要進一步處理;)

+0

不錯的一個。你應該在正則表達式及其工作方式上添加簡短的解釋。 –

相關問題