2017-09-25 43 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

不错的一个。你应该在正则表达式及其工作方式上添加简短的解释。 –

相关问题