简体   繁体   English

如何在一个句子中的每个元音后检测并打印第一个字母?

[英]How to detect and print first letter after each vowel in a sentence?

I wrote this code to detect and print the first letter after each vowel. 我写了这段代码来检测和打印每个元音后的第一个字母。 It works except when I input a word with two consecutive vowels. 它的工作原理除非我输入一个带有两个连续元音的单词。 It ignores the second vowel. 它忽略了第二个元音。 For example, if I input 'school year' the result should be: 例如,如果我输入“学年”,结果应为:

o
l
a
r

but I only get 但我只能得到

o
a

So what am I doing wrong? 那么我做错了什么? I am fairly new to python and I am still learning. 我对python很新,我还在学习。

def find_after_vowel(word):
for match in re.findall(r"[ouieaOUIEA](\w{1}|\s)", word):
      print (match)

You can use finditer and the start method of the resulting match objects to find the index of each match, and then use that to get the letter after each vowel: 您可以使用finditer和生成的匹配对象的start方法来查找每个匹配的索引,然后使用它来获取每个元音之后的字母:

import re

def find_after_vowel(word):
    for match in re.finditer(r"[ouieaOUIEA]", word):
          print word[match.start()+1] 

find_after_vowel("school year")

Which will output: 哪个会输出:

o
l
a
r

If you want it to return a list instead of printing the results, use: 如果您希望它返回列表而不是打印结果,请使用:

import re

def find_after_vowel(word):
    after_vowels = []
    for match in re.finditer(r"[ouieaOUIEA]", word):
          after_vowels.append(word[match.start()+1])
    return after_vowels

after_vowels = find_after_vowel("school year")
print after_vowels

Which will output: 哪个会输出:

['o', 'l', 'a', 'r']

试试以下正则表达式: [ouieaOUIEA]([^ouieaOUIEA]|\\s)

If I understand you right, you can try this: 如果我理解你,你可以试试这个:

import re

def find_after_vowel(word):
    index = re.search(r'[ouieaOUIEA]', word).span()[0] + 1
    return word[index]

print(find_after_vowel('test')) # s
print(find_after_vowel('abc')) # b
print(find_after_vowel('def')) # f
print(find_after_vowel('abcdef')) # b

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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