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

标签 python regex python-3.x

我编写此代码是为了检测并打印每个元音后面的第一个字母。除非我输入带有两个连续元音的单词,否则它会起作用。它忽略第二个元音。例如,如果我输入“学年”,结果应该是:

o
l
a
r

但我只得到

o
a

那我做错了什么?我对 python 还很陌生,而且还在学习中。

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

最佳答案

您可以使用 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")

将输出:

o
l
a
r

如果您希望它返回列表而不是打印结果,请使用:

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

将输出:

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

关于python - 如何检测并打印句子中每个元音后面的第一个字母?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43306921/

相关文章:

Python-使用列表理解关闭同时打开的一堆文本文件

python - 如何通过字典值搜索包含嵌套字典的列表,并返回包含字典元素的列表的索引

python - QSqlTableModel setFilter 参数过多

jquery - 正则表达式匹配 @"*"

regex - 如何删除Lua中括号内的文本?

regex - 有没有办法比较正则表达式反向引用?

python - 如何按列的绝对值对numpy数组进行排序?

python-3.x - “KerasClassifier”对象没有属性 'loss'

python - 获取 Django 中选定的多个复选框的值

Python:如果行中只有 1 个单词,则替换数据框/列中的字符串