删除其中有两个连续元音的单词 [英] Delete words which have 2 consecutive vowels in it

查看:127
本文介绍了删除其中有两个连续元音的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要的是删除其中有两个以上连续元音的单词.所以输入:

What i want is remove the words which have more than two consecutive vowels in it. So input:

s = " There was a boat in the rain near the shore, by some mysterious lake"

输出:

[boat,rain,near,mysterious] 

这是我的代码. 我只是想知道是否有更好的方法可以做到这一点,或者它是否足够有效?是否可以使用python dict做到这一点,或者列表还可以吗? :)我是python的新手,是的. :)评论会很好.

So here is my code. I was just wondering if there is any better way to do this or is this efficient enough.And if you can do this with python dict or lists are ok? :) I'm new to python so yeah. :) comments would be nice.

def change(s):
vowel = ["a","e","i","o","u"]
words = []
a = s[:].replace(",","").split()
for i in vowel:
    s = s.replace(i, "*").replace(",","")
for i,j in enumerate(s.split()):
    if "**" in j:
        words.append(a[i])
return words

推荐答案

使用集合:

使用 set.intersection 的第一种方法只会找到非相同的连续对,因此oo不会匹配:

First method using set.intersection will only find non identical consecutive pairs so oo would not be a match:

s = " There was a boat in the rain near the shore, by some mysterious lake"
vowels = "aeiouAEIOU"
print([x for x in s.split() if any(len(set(x[i:i+2]).intersection(vowels))==  2 for i in range(len(x))) ])
['boat', 'rain', 'near', 'mysterious']

方法2使用 set.issubset ,因此现在连续相同对将被视为匹配项.

Method 2 uses set.issubset so now identical consecutive pairs will be considered a match.

set.issubset与使用yield from python 3语法的函数结合使用,这可能更合适,并且确实可以捕获重复的相同元音:

using set.issubset with a function using the yield from python 3 syntax which might be more appropriate and indeed to catch repeated identical vowels :

vowels = "aeiouAEIOU"
def get(x, step):
    yield from (x[i:i+step] for i in range(len(x[:-1])))

print([x for x in s.split() if any(set(pr).issubset(vowels) for pr in get(x, 2))])

或再次在单个列表中:

print([x for x in s.split() if any(set(pr).issubset(vowels) for pr in (x[i:i+2] for i in range(len(x[:-1]))))])

最后将元音设为一个集合,并检查它是否为 set.issuperset 任意一对字符:

Finally make vowels a set and check if it is a set.issuperset of any pair of chars:

vowels = {'a', 'u', 'U', 'o', 'e', 'i', 'A', 'I', 'E', 'O'}


def get(x, step):
    yield from (x[i:i+step] for i in range(len(x[:-1])))

print([x for x in s.split() if any(vowels.issuperset(pr) for pr in get(x, 2))])

这篇关于删除其中有两个连续元音的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆