【问题标题】:From a string, how do you return only the words that don't begin with a vowel?从字符串中,如何只返回不以元音开头的单词?
【发布时间】:2019-11-27 19:23:59
【问题描述】:

我有一个字符串,例如“狗是好宠物”

我希望能够只返回以辅音开头的单词。 ["dog", "good", "pet"] 作为列表

def consonant_first(newstr):
    for char in newstr.split():
        if char[0] in newstr.split() ==  vowels1:
            return newstr.split() 
print(newstr)

【问题讨论】:

标签: python string


【解决方案1】:

只测试列表理解中的第一个字母:

s = "A dog is a good pet"

def consonant_first(newstr):
    return [word for word in s.split() if  word[0].lower() not in 'aeiou']

print(consonant_first(s))

确保针对所有情况进行测试,以便您捕获A

结果:

['dog', 'good', 'pet']

【讨论】:

  • 如果我必须把它写成一个函数 def consonant_first():
  • 需要整个句子。
  • @Trevor713 查看编辑 - 您可以将其包装在 def: 中并返回列表。
【解决方案2】:

这是一个使用迭代器的解决方案,以防您计划处理大量文本:

import re

def find_consonant_words(text: str):
    vowels = set("aeiou")

    for m in re.finditer('\S+', text):
        w = m.group(0)
        if w[0].lower() not in vowels:
            yield w

string = "A very long text: a dog is a good pet"

for w in find_consonant_words(string):
    print(w)

# get it all as a list
consonant_words = list(find_consonant_words(string))
print(consonant_words)

输出:

very
long
text:
dog
good
pet
['very', 'long', 'text:', 'dog', 'good', 'pet']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-22
    • 1970-01-01
    • 1970-01-01
    • 2023-01-07
    • 2016-01-13
    • 1970-01-01
    • 2012-10-01
    • 1970-01-01
    相关资源
    最近更新 更多