Read three hundred and sixty-four | return two

two hundred

Posts

zero

TA resources

A grain of gold sand (advanced)

Building owner
 

Interesting micro project, easy to learn Python chapters 8-15 [Copy Link]

The content of Chapter 8 is to find and replace. The author leads to the content of this chapter through the song Apple and Banana.

In this chapter, we will implement a program that selects a text and replaces all vowels in the text with the given - v or - vowel option.

The main contents include: changing the string, using str.replace() method, using str.translate(), other methods to change the string, six methods to replace vowels, and reconstructing with tests.

Through the study of this chapter, we will further learn the text processing methods, and learn a variety of methods to replace text: including iterating each character, using the str.replace() method, using the str.translate() method, using list derivation, using list derivation with functions, using the map() function, using map() with named functions, and using regular expressions. One way of program implementation is as follows:

 #!/ usr/bin/env python3 """Apples and Bananas""" import argparse import os # -------------------------------------------------- def get_args(): """get command-line arguments""" parser = argparse.ArgumentParser( description='Apples and bananas', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('text',  metavar='text', help='Input text or file') parser.add_argument('-v', '--vowel', help='The vowel to substitute', metavar='vowel', type=str, default='a', choices=list('aeiou')) args = parser.parse_args() if os.path.isfile(args.text): args.text = open(args.text).read().rstrip() return args # -------------------------------------------------- def main(): """Make a jazz noise here""" args = get_args() text = args.text vowel = args.vowel new_text = [] for char in text: if char in 'aeiou': new_text.append(vowel) elif char in 'AEIOU': new_text.append(vowel.upper()) else: new_text.append(char) print(''.join(new_text)) # -------------------------------------------------- if __name__ == '__main__': main()

The content of Chapter 9 is to generate random sarcasm with word list. The author introduces the content of random event handling in this chapter through dial curse.

In this chapter, we will implement a program. It will randomly select adjectives and nouns to create slanderous nicknames to taunt users.

The main contents include: writing abuse.py, verifying actual parameters, importing random modules and generating seeds, defining adjectives and nouns, collecting random samples and selecting them, formatting the output, using parser. error (), program exit value and STDERR, using random. seed () to control randomness, using range () to iterate and use discard variables, and constructing mocking statements.

Through the study of this chapter, we will learn to use parser. error () from argpars, throw errors, use random seeds to control randomness, randomly select and sample from python lists, use the for loop to iterate an algorithm for a specific number of times, and format the output string. The program is implemented as follows:

 #!/ usr/bin/env python3 """Heap abuse""" import argparse import random # -------------------------------------------------- def get_args(): """Get command-line arguments""" parser = argparse.ArgumentParser( description='Heap abuse', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-a', '--adjectives', help='Number of adjectives', metavar='adjectives', type=int, default=2) parser.add_argument('-n', '--number', help='Number of insults', metavar='insults', type=int, default=3) parser.add_argument('-s', '--seed', help='Random seed', metavar='seed', type=int, default=None) args = parser.parse_args() if args.adjectives < 1: parser.error(f'--adjectives "{args.adjectives}" must be > 0') if args.number < 1: parser.error(f'--number "{args.number}" must be > 0') return args # -------------------------------------------------- def main(): """Make a jazz noise here""" args = get_args() random.seed(args.seed) adjectives = """ bankrupt base caterwauling corrupt cullionly detestable dishonest false filthsome filthy foolish foul gross heedless indistinguishable infected insatiate irksome lascivious lecherous loathsome lubbery old peevish rascaly rotten ruinous scurilous scurvy slanderous sodden-witted thin-faced toad-spotted unmannered vile wall-eyed """.strip().split() nouns = """ Judas Satan ape ass barbermonger beggar block boy braggart butt carbuncle coward coxcomb cur dandy degenerate fiend fishmonger fool gull harpy jack jolthead knave liar lunatic maw milksop minion ratcatcher recreant rogue scold slave swine traitor varlet villain worm """.strip().split() for _ in range(args.number): adjs = ', '.join(random.sample(adjectives, k=args.adjectives)) print(f'You {adjs} {random.choice(nouns)}!') # -------------------------------------------------- if __name__ == '__main__': main()

Chapter 10 is about randomly changing strings. The author introduces the content of this chapter through the telephone game program.

In this chapter, we will simulate this phone game program. In this game, a row or a circle of people will whisper a secret message. Each time the message is spread, it will change in an unpredictable way. The last person who receives the message will say it out loud.

The main contents include: writing telephone. py, calculating the number of changes, changing space, selecting characters to change, changing strings, using list instead of str.

Through the study of this chapter, we will learn to round numbers, use the srting module, modify strings and lists, and make random changes. The program is implemented as follows:

 #!/ usr/bin/env python3 """Telephone""" import argparse import os import random import string # -------------------------------------------------- def get_args(): """Get command-line arguments""" parser = argparse.ArgumentParser( description='Telephone', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('text',  metavar='text', help='Input text or file') parser.add_argument('-s', '--seed', help='Random seed', metavar='seed', type=int, default=None) parser.add_argument('-m', '--mutations', help='Percent mutations', metavar='mutations', type=float, default=0.1) args = parser.parse_args() if not 0 <= args.mutations <= 1: parser.error(f'--mutations "{args.mutations}" must be between 0 and 1') if os.path.isfile(args.text): args.text = open(args.text).read().rstrip() return args # -------------------------------------------------- def main(): """Make a jazz noise here""" args = get_args() text = args.text random.seed(args.seed) alpha = ''.join(sorted(string.ascii_letters + string.punctuation)) len_text = len(text) num_mutations = round(args.mutations * len_text) new_text = text for i in random.sample(range(len_text), num_mutations): new_char = random.choice(alpha.replace(new_text[i], '')) new_text = new_text[:i] + new_char + new_text[i + 1:] print(f'You said: "{text}"\nI heard : "{new_text}"') # -------------------------------------------------- if __name__ == '__main__': main()

Chapter 11 is about writing and testing functions. The author leads to the content of this chapter through the song "There are 99 bottles of beer on the wall".

In this chapter, we will implement a song generation program. It takes an option - n or - num, which must be a positive int, and the program prints all sections counted backwards from - num to 1. There should be two new lines between each section. There can only be one new line after the last section, and print "No more bottoms of beer on the wall".

The main contents include: writing bottoms.py, reverse counting, writing functions, writing tests for verse (), using verse () functions, test driven development, verse () functions, traversing song sections, etc.

Through learning in this chapter, we will learn how to generate a list composed of decreasing numbers, write a function to create a section of the song, use tests to verify when the section is correct, and explore how to write the for loop as a list derivation, and then as a map(). The program is implemented as follows:

 #!/ usr/bin/env python3 """Bottles of beer song""" import argparse # -------------------------------------------------- def get_args(): """Get command-line arguments""" parser = argparse.ArgumentParser( description='Bottles of beer song', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-n', '--num', metavar='number', type=int, default=10, help='How many bottles') args = parser.parse_args() if args.num < 1: parser.error(f'--num "{args.num}" must be greater than 0') return args # -------------------------------------------------- def main(): """Make a jazz noise here""" args = get_args() print('\n\n'.join(map(verse, range(args.num, 0, -1)))) # -------------------------------------------------- def verse(bottle): """Sing a verse""" next_bottle = bottle - 1 s1 = '' if bottle == 1 else 's' s2 = '' if next_bottle == 1 else 's' num_next = 'No more' if next_bottle == 0 else next_bottle return '\n'.join([ f'{bottle} bottle{s1} of beer on the wall,', f'{bottle} bottle{s1} of beer,', f'Take one down, pass it around,', f'{num_next} bottle{s2} of beer on the wall!', ]) # -------------------------------------------------- def test_verse(): """Test verse""" last_verse = verse(1) assert last_verse == '\n'.join([ '1 bottle of beer on the wall,', '1 bottle of beer,', 'Take one down, pass it around,', 'No more bottles of beer on the wall!' ]) two_bottles = verse(2) assert two_bottles == '\n'.join([ '2 bottles of beer on the wall,', '2 bottles of beer,', 'Take one down,  pass it around,', '1 bottle of beer on the wall!' ]) # -------------------------------------------------- if __name__ == '__main__': main()

Chapter 12 is random capital text. The author introduces the content of this chapter through the story of kidnappers sending redeeming gold bars.

In this chapter, we will implement a program. It can replace text with random uppercase letters.

The main contents include: writing ransom. py, modifying text, tossing a coin, creating a new string, traversing elements in the sequence, writing functions to select letters, writing another method of list. append(), using str instead of list, using list parsing, using map() function to compare, etc.

Through the learning of this chapter, we will learn to use the random module to "flip a coin" vividly, choose between two choices, explore the method of generating new strings from existing strings, and combine with random decision-making to study the similarity of for loops, list derivation and map() functions. One of the programs is as follows:

 #!/ usr/bin/env python3 """Ransom note""" import argparse import os import random # -------------------------------------------------- def get_args(): """Get command-line arguments""" parser = argparse.ArgumentParser( description='Ransom Note', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('text',  metavar='text', help='Input text or file') parser.add_argument('-s', '--seed', help='Random seed', metavar='int', type=int, default=None) args = parser.parse_args() if os.path.isfile(args.text): args.text = open(args.text).read().rstrip() return args # -------------------------------------------------- def main(): """Make a jazz noise here""" args = get_args() random.seed(args.seed) # Method 1: Iterate each character, add to list ransom = [] for char in args.text: ransom.append(choose(char)) print(''.join(ransom)) # -------------------------------------------------- def choose(char): """Randomly choose an upper or lowercase letter to return""" return char.upper() if random.choice([0, 1]) else char.lower() # -------------------------------------------------- def test_choose(): """Test choose""" state = random.getstate() random.seed(1) assert choose('a') == 'a' assert choose('b') == 'b' assert choose('c') == 'C' assert choose('d') == 'd' random.setstate(state) # -------------------------------------------------- if __name__ == '__main__': main()

Chapter 13 is about algorithm design. The author leads to the theme of this chapter through the song "Twelve Days of Christmas".

In this chapter, we will implement such an algorithm. Generate a song for a given number of days. It will generate Twelve Days of Christmas until the given date, which is specified by the - n or - num argument.

The main contents include: writing twelve_days.py, counting, creating ordinal values, making sections, using the verse () function, generating sections, printing sections, and so on.

Through the learning in this chapter, we will learn to create an algorithm for generating songs with a given number of days in the range of 1-12, arrange a list in reverse order, use the range() function, and write the text to a file or STDOUT. The program is implemented as follows:

 #!/ usr/bin/env python3 """Twelve Days of Christmas""" import argparse import sys # -------------------------------------------------- def get_args(): """Get command-line arguments""" parser = argparse.ArgumentParser( description='Twelve Days of Christmas', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-n', '--num', help='Number of days to sing', metavar='days', type=int, default=12) parser.add_argument('-o', '--outfile', help='Outfile', metavar='FILE', type=argparse.FileType('wt'), default=sys.stdout) args = parser.parse_args() if args.num not in range(1, 13): parser.error(f'--num "{args.num}" must be between 1 and 12') return args # -------------------------------------------------- def main(): """Make a jazz noise here""" args = get_args() verses = map(verse, range(1, args.num + 1)) print('\n\n'.join(verses), file=args.outfile) # -------------------------------------------------- def verse(day): """Create a verse""" ordinal = [ 'first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth', 'eleventh', 'twelfth' ] gifts = [ 'A partridge in a pear tree.', 'Two turtle doves,', 'Three French hens,', 'Four calling birds,', 'Five gold rings,', 'Six geese a laying,', 'Seven swans a swimming,', 'Eight maids a milking,', 'Nine ladies dancing,', 'Ten lords a leaping,', 'Eleven pipers piping,', 'Twelve drummers drumming,', ] lines = [ f'On the {ordinal[day - 1]} day of Christmas,', 'My true love gave to me,' ] lines.extend(reversed(gifts[:day])) if day > 1: lines[-1] = 'And ' + lines[-1].lower() return '\n'.join(lines) # -------------------------------------------------- def test_verse(): """Test verse""" assert verse(1) == '\n'.join([ 'On the first day of Christmas,', 'My true love gave to me,', 'A partridge in a pear tree.' ]) assert verse(2) == '\n'.join([ 'On the second day of Christmas,', 'My true love gave to me,', 'Two turtle doves,', 'And a partridge in a pear tree.' ]) # -------------------------------------------------- if __name__ == '__main__': main()

Chapter 14 is about using regular expressions to create rhyming words. The author introduces the content of this chapter through a rhyme game involved in the movie Princess Bride.

In this chapter, we will implement a program to select a given word and create a word that rhymes with it, using regular expressions.

The main contents include: writing rhymer.py, decomposing words, using regular expressions, using capture groups, authenticity, stemming words, formatting and commenting regular expressions, using the stemmer() function outside the program, creating rhyming strings, and stemmer() without regular expressions

Through the study of this chapter, we will learn to write and use regular expressions, use guard statements in list derivation, explore the similarity between list derivation with guard statements and filter() function, and consider "authenticity" when evaluating python types in Boolean context. The program is implemented as follows:

 #!/ usr/bin/env python3 """Make rhyming words""" import argparse import re 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() prefixes = list('bcdfghjklmnpqrstvwxyz') + ( '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) if rest: print('\n'.join(sorted([p + rest for p in prefixes if p != start]))) else: print(f'Cannot rhyme "{args.word}"') # -------------------------------------------------- def stemmer(word): """Return leading consonants (if any), and 'stem' of word""" word = word.lower() vowels = 'aeiou' consonants = ''.join( [c for c in string.ascii_lowercase if c not in vowels]) pattern = ( '([' + consonants + ']+)?' #  capture one or more, optional '([' + vowels     + '])'   # capture at least one vowel '(.*)'                     # capture zero or more of anything ) pattern = f'([{consonants}]+)? ([{vowels}])(.*)' match = re.match(pattern, word) if match: p1 = match.group(1) or '' p2 = match.group(2) or '' p3 = match.group(3) or '' return (p1, p2 + p3) else: return (word, '') # -------------------------------------------------- def test_stemmer(): """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') == ('123', '') # -------------------------------------------------- if __name__ == '__main__': main()

Chapter 15 is more about regular expressions. The author introduces the content of this chapter through the fact that local people will omit the "g" at the end of the word ending with "ing".

In this chapter, we will implement a program. It receives an input as a single position argument, replaces the two syllable words ending with "ing" in the text with ('), and changes "you" to "y'all".

The main contents include: writing friar.py, using regular expressions to disassemble text, shorthand classes, negative shorthand classes, using re.split() with captured regular expressions, writing fry() functions, using fry() functions, and writing fry() functions with regular expressions.

Through this chapter, we will learn more about regular expressions, learn to use re.match() and re.search() to find patterns anchored at the beginning of a string or anywhere in a string, learn how the $symbol in a regular expression anchors the pattern to the end of a character, learn how to use re.split() to disassemble a string, and explore how to write to find the double syllable "ing" Or the word "you" manual solution. The program is implemented as follows:

 #!/ usr/bin/env python3 """Kentucky Friar""" import argparse import os import re # -------------------------------------------------- def get_args(): """Get command-line arguments""" parser = argparse.ArgumentParser( description='Southern fry text', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('text',  metavar='text', help='Input text or file') args = parser.parse_args() if os.path.isfile(args.text): args.text = open(args.text).read() return args # -------------------------------------------------- def main(): """Make a jazz noise here""" args = get_args() for line in args.text.splitlines(): print(''.join(map(fry, re.split(r'(\W+)', line.rstrip())))) # -------------------------------------------------- def fry(word): """Drop the `g` from `-ing` words, change `you` to `y'all`""" ing_word = re.search('(.+)ing$', word) you = re.match('([Yy])ou$', word) if ing_word: prefix = ing_word.group(1) if re.search('[aeiouy]',  prefix, re.IGNORECASE): return prefix + "in'" elif you: return you.group(1) + "'all" return word # -------------------------------------------------- def test_fry(): """Test fry""" assert fry('you') == "y'all" assert fry('You') == "Y'all" assert fry('your') == 'your' assert fry('fishing') == "fishin'" assert fry('Aching') == "Achin'" assert fry('swing') == "swing" # -------------------------------------------------- if __name__ == '__main__': main()



 

 

 

This post is from Embedded System Forum

Latest reply

It seems that I have spent a lot of time to sum up all the things I learned in the three chapters at one time!   details reply Published on 5 days ago
give the thumbs-up follow

reply
report

Moderator

sofa
 

In fact, what we need to learn is object-oriented methods and various third-party methods

This post is from Embedded System Forum
 
Personal signature

Keep moving forward on the road of love and spread light in the fog of life

 

reply

Moderator

Bench
 

It seems that I have spent a lot of time to sum up all the things I learned in the three chapters at one time!

This post is from Embedded System Forum
 
 
 

reply
You need to log in before you can reply Sign in | register

look around
Find Data Book?

EEWorld Datasheet Technical Support

Related articles More>>
close
Recommended by webmaster Previous one /10  Next
Copyright Electronic Engineering World Beijing B2-20211791 Jing ICP Bei 10001474-1 TSSP [2006] No. 258 Jinggong Network Anbei No. 11010802033920 Copyright © 2005-2024 EEWORLD.com.cn, Inc. All rights reserved
Quick reply Back to top Back to list