簡體   English   中英

Python 中的條件,字母按特定順序

[英]Condition in Python with letters in a specific order

我正在嘗試在語料庫中查找具有按該順序出現在單詞中的字母(特別是 aeiouy)的單詞(例如滑稽地)。 到目前為止,我有以下代碼,但正在努力使其具有它們需要按以下順序排列的條件。

english = nltk.corpus.words.words()
words = [w for w in english if re.search(r'[aeiouy]',w)]

有什么簡單的方法可以做到這一點?

試試re.search(r'a[b-zB-Z]*e[b-df-zB-DF-Z]*i[b-df-hj-zB-DF-HJ-Z]*o[b-df-hj-np-zB-DF-HJ-NP-Z]*u[b-df-hj-np-tv-zB-DF-HJ-NP-TV-Z]*y',w)允許字母之間的一些(最終)字符([a-zA-Z])。

丑是不是。

但是,如果您事先確定所有字符都在 [a-zA-Z] 中,則可以簡化: re.search(r'a[^a]*e[^ae]*i[^aei]*o[^aeio]*u[^aeiou]*y',w)

re.search('a[^iouy]*e[^aouy]*i[^aeuy]*o[^aeiy]*u[^aeio]*y', w, re.I)

這是無需使用 RegEx 的最佳方法:

def verifyString(s):
    current_vowel = 'a'
    vowels= 'aeiouy'
    for c in s:
        if c==current_vowel:
            if len(vowels)==1:
                return True
            vowels = vowels[1:]
            current_vowel = vowels[0]
    return False

如果您希望訂單嚴格,可以使用:

def verifyStringStrict(s):
    current_vowel = 'a'
    vowels= 'aeiouy'
    for c in s:
        if c in vowels:
            if c==current_vowel:
                if len(vowels)==1:
                    return True
                vowels = vowels[1:]
                current_vowel = vowels[0]
            else:
                return False
    return False

你將會有:

verifyString('saseqiqoqusyq') #True
verifyStringStrict('ssasdediqqodudyd') #True
verifyString('zazezizzudozyz') #False
verifyStringStrict('daezizzuzozyz') #False
verifyString('waewwiwuowuwcyd') #True
verifyStringStrict('waeiwuwowuwxyx') #False

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM