简体   繁体   中英

How to check if string consist of consonant, vowel and consonant?

Lets say I have a list of strings verbs = ["win", "dig", "be", "go", "break] etc. I figured out how to duplicate last letter and add "ing" to them. However how can I check if characters in those strings consisting of consonant-vowel-consonat? I have two lists:

vowel = ["a", "e", "i", "o", "u"]
consonant = ["b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z"]

and here is code sample:

for ver in verbs:
    if verb "I DON'T KNOW WHAT TO TYPE HERE":
        verb = verb[:len(verb)] + verb[len(verb) - 1: len(verb)] + "ing"
        - then do sth

I'd use sets , for fast membership testing:

import string

vowel = set("aeiou")
consonant = set(string.ascii_lowercase) - vowel   # all letters that are not vowels

then just see if those last 3 letters are in the sets:

if len(verb) > 2 and verb[-3] in consonant and verb[-2] in vowel and verb[-1] in consonant:
    verb += verb[-1] + 'ing'

or a little more compact using strict subset testing:

if len(verb) > 2 and {verb[-3], verb[-1]} <= consonant and verb[-2] in vowel:
    verb += verb[-1] + 'ing'

The verb += verb[-1] + 'ing' statement uses augmented assignment to append the last letter plus 'ing' to the verb string value. Negative indices count from the end of the sequence, so -1 gives you the last letter in a string:

>>> verb[-1]
'k'

Demo:

>>> for verb in verbs:
...     if len(verb) > 2 and {verb[-3], verb[-1]} <= consonant and verb[-2] in vowel:
...         verb += verb[-1] + 'ing'
...     else:
...         verb += 'ing'
...     print(verb)
...
winning
digging
being
going
breaking

I would suggest that use some NLP package like NodeBox or nltk to do this instead of writing custom code to append ing . There might be some case that you may miss.

Some answers here might be helpful:

Using NLTK and WordNet; how do I convert simple tense verb into its present, past or past participle form?

This library is also very helpful https://www.nodebox.net/code/index.php/Linguistics#verb_conjugation

An example:

import en
print en.verb.present_participle("be")

being

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM