创建一个包含3个以上元音的所有单词(包括连字符单词)的列表

2024-03-28 19:03:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这根绳子

tw =('BenSasse, well I did teach her the bend-and-snap https://twitter.com/bethanyshondark/status/903301101855928322 QT @bethanyshondark Is Reese channeling @BenSasse https://acculturated.com/reese-witherspoons-daughter-something-many-celebrity-children-lack-work-ethic/ , Twitter for Android')

我需要创建一个列表,列出所有超过3个元音的单词。请帮帮我!你知道吗


Tags: andthehttpscomtwittertwsnapwell
2条回答

我建议你先创建一个所有元音的列表:

vowels = ['a','e','i','o','u']

好吧,字母列表(Char)实际上和字符串是一样的,所以我只需要做以下操作:

vowels = "aeiou"

在那之后,我会试着把你的字串分成几个字。让我们试试乔兰·比斯利建议的tw.split()。它返回:

['BenSasse,', 'well', 'I', 'did', 'teach', 'her', 'the', 'bend-and-snap', 'https://twitter.com/bethanyshondark/status/903301101855928322', 'QT', '@bethanyshondark', 'Is', 'Reese', 'channeling', '@BenSasse', 'https://acculturated.com/reese-witherspoons-daughter-something-many-celebrity-children-lack-work-ethic/', ',', 'Twitter', 'for', 'Android']

你能接受这句话吗?请注意,每个链接都是一个“单词”。我想这没问题。你知道吗

如果我们用for循环访问每个单词,我们就可以用内部for循环访问每个字母。但是在我们开始之前,我们需要跟踪所有接受的3个或更多元音的单词,所以做一个新的列表:final_list = list()。现在:

for word in tw.split():
    counter=0 #  Let's keep track of how many vowels we have in a word
    for letter in word:
        if letter in vowels:
            counter = counter+1
    if counter >= 3:
        final_list.append(word) #  Add the word if 3 or more vowels.

如果您现在打印:print(final_list)您应该得到:

['BenSasse,', 'bend-and-snap', 'https://twitter.com/bethanyshondark/status/903301101855928322', '@bethanyshondark', 'Reese', 'channeling', '@BenSasse', 'https://acculturated.com/reese-witherspoons-daughter-something-many-celebrity-children-lack-work-ethic/']

可以将re.findall与以下正则表达式一起使用:

import re
re.findall(r'(?:[a-z-]*[aeiou]){3,}[a-z-]*', tw, flags=re.IGNORECASE)

这将返回:

['BenSasse', 'bend-and-snap', 'bethanyshondark', 'bethanyshondark', 'Reese', 'channeling', 'BenSasse', 'acculturated', 'reese-witherspoons-daughter-something-many-celebrity-children-lack-work-ethic', 'Android']

相关问题 更多 >