concept vowel in category python

appears as: vowel, vowels, vowels
Tiny Python Projects: Learn coding and testing with puzzles and games

This is an excerpt from Manning's book Tiny Python Projects: Learn coding and testing with puzzles and games.

Your program should be called crowsnest.py. It will accept a single positional argument and will print the given argument inside the “Ahoy” bit, along with the word “a” or “an” depending on whether the argument starts with a consonant or a vowel.

  • Verify that the --vowel option is in the set of vowels “a,” “e,” “i,” “o,” and “u”
  • Replace all instances of vowels in the input text with the specified (or default) --vowel argument
  • I declared the new_char() function inside main() because I wanted to reference the vowel variable inside the function, as shown in figure 8.6. Because new_char() “closes” around the vowel, it is a special type of function called a closure.

    Figure 8.6 The new_char() function can only be seen within the main() function. It creates a closure because it references the vowel variable. Code outside of main() cannot see or call new_char().

    If we don’t write this as a closure, we will have to pass the vowel as an argument:

    #!/usr/bin/env python3
    """Make rhyming words"""
     
    import argparse
    import re                                                                    #1
    import string
     
     
    # --------------------------------------------------
    def get_args():
        """get command-line arguments"""
     
        parser = argparse.ArgumentParser(
            description='Make rhyming "words"',
            formatter_class=argparse.ArgumentDefaultsHelpFormatter)
     
        parser.add_argument('word', metavar='word', help='A word to rhyme')
     
        return parser.parse_args()
     
     
    # --------------------------------------------------
    def main():
        """Make a jazz noise here"""
     
        args = get_args()                                                        #2
        prefixes = list('bcdfghjklmnpqrstvwxyz') + (                             #3
            'bl br ch cl cr dr fl fr gl gr pl pr sc '
            'sh sk sl sm sn sp st sw th tr tw thw wh wr '
            'sch scr shr sph spl spr squ str thr').split()
     
        start, rest = stemmer(args.word)                                         #4
        if rest:                                                                 #5
     
            print('\n'.join(sorted([p + rest for p in prefixes if p != start]))) #6
        else:
            print(f'Cannot rhyme "{args.word}"')                                 #7
     
     
    # --------------------------------------------------
    def stemmer(word):
        """Return leading consonants (if any), and 'stem' of word"""
     
        word = word.lower()                                                      #8
        vowels = 'aeiou'                                                         #9
        consonants = ''.join(                                                    #10
            [c for c in string.ascii_lowercase if c not in vowels])
        pattern = (                                                              #11
            '([' + consonants + ']+)?' # capture one or more, optional
            '([' + vowels     + '])'   # capture at least one vowel
            '(.*)'                     # capture zero or more of anything
        )
     
        match = re.match(pattern, word)                                          #12
        if match:                                                                #13
            p1 = match.group(1) or ''                                            #14
            p2 = match.group(2) or ''
            p3 = match.group(3) or ''
            return (p1, p2 + p3)                                                 #15
        else:
            return (word, '')                                                    #16
     
     
    # --------------------------------------------------
    def test_stemmer():                                                          #17
        """test the stemmer"""
     
        assert stemmer('') == ('', '')
        assert stemmer('cake') == ('c', 'ake')
        assert stemmer('chair') == ('ch', 'air')
        assert stemmer('APPLE') == ('', 'apple')
        assert stemmer('RDNZL') == ('rdnzl', '')
        assert stemmer('123') == ('', '')
     
     
    # --------------------------------------------------
    if __name__ == '__main__':
        main()
    sitemap

    Unable to load book!

    The book could not be loaded.

    (try again in a couple of minutes)

    manning.com homepage