This commit is contained in:
2024-09-14 12:28:16 +02:00
parent 148cd55409
commit e420899612
5 changed files with 129 additions and 0 deletions

View File

@ -0,0 +1,22 @@
# Regular Expressions (sometimes shortened to regexp, regex, or re) are a tool for matching patterns in text. In Python, we have the re module. The applications for regular expressions are wide-spread, but they are fairly complex, so when contemplating using a regex for a certain task, think about alternatives, and come to regexes as a last resort.
# An example regex is r"^(From|To|Cc).*?python-list@python.org" Now for an explanation: the caret ^ matches text at the beginning of a line. The following group, the part with (From|To|Cc) means that the line has to start with one of the words that are separated by the pipe |. That is called the OR operator, and the regex will match if the line starts with any of the words in the group. The .*? means to un-greedily match any number of characters, except the newline \n character. The un-greedy part means to match as few repetitions as possible. The . character means any non-newline character, the * means to repeat 0 or more times, and the ? character makes it un-greedy.
# So, the following lines would be matched by that regex: From: python-list@python.org To: !asp]<,. python-list@python.org
# A complete reference for the re syntax is available at the python docs. https://docs.python.org/3/library/re.html#regular-expression-syntax%22RE%20syntax
# As an example of a "proper" email-matching regex (like the one in the exercise), see this
# Exercise: make a regular expression that will match an email
import re
def test_email(your_pattern):
pattern = re.compile(your_pattern)
emails = ["john@example.com", "python-list@python.org", "wha.t.`1an?ug{}ly@email.com"]
for email in emails:
if not re.match(pattern, email):
print("You failed to match %s" % (email))
elif not your_pattern:
print("Forgot to enter a pattern!")
else:
print("Pass")
# Your pattern here!
pattern = r"\"?([-a-zA-Z0-9.`?{}]+@\w+\.\w+)\"?"
test_email(pattern)

View File

@ -0,0 +1,44 @@
# When programming, errors happen. It's just a fact of life. Perhaps the user gave bad input. Maybe a network resource was unavailable. Maybe the program ran out of memory. Or the programmer may have even made a mistake!
# Python's solution to errors are exceptions. You might have seen an exception before.
#print(a)
#error
# Traceback (most recent call last):
# File "", line 1, in
# NameError: name 'a' is not defined
# But sometimes you don't want exceptions to completely stop the program. You might want to do something special when an exception is raised. This is done in a try/except block.
# Here's a trivial example: Suppose you're iterating over a list. You need to iterate over 20 numbers, but the list is made from user input, and might not have 20 numbers in it. After you reach the end of the list, you just want the rest of the numbers to be interpreted as a 0. Here's how you could do that:
def do_stuff_with_number(n):
print(n)
def catch_this():
the_list = (1, 2, 3, 4, 5)
for i in range(20):
try:
do_stuff_with_number(the_list[i])
except IndexError: # Raised when accessing a non-existing index of a list
do_stuff_with_number(0)
catch_this()
# Exercise
# Handle all the exception! Think back to the previous lessons to return the last name of the actor.
# Setup
actor = {"name": "John Cleese", "rank": "awesome"}
# Function to modify!!!
def get_last_name():
try:
return actor["last_name"]
except:
return actor["name"].split()[1]
# Test code
get_last_name()
print("All exceptions caught! Good job!")
print("The actor's last name is %s" % get_last_name())

View File

@ -0,0 +1,22 @@
#Sets are lists with no duplicate entries. Let's say you want to collect a list of words used in a paragraph:
print(set("my name is Eric and Eric is my name".split()))
# Sets are a powerful tool in Python since they have the ability to calculate differences and intersections between other sets. For example, say you have a list of participants in events A and B:
#To find out which members attended both events, you may use the "intersection" method:
a = set(["Jake", "John", "Eric"])
print(a)
b = set(["John", "Jill"])
print(b)
print(a.intersection(b))
#To find out which members attended only one of the events, use the "symmetric_difference" method:
print(a.symmetric_difference(b))
#To find out which members attended only one event and not the other, use the "difference" method:
print(a.difference(b))
#To receive a list of all participants, use the "union" method:
print(a.union(b))

View File

@ -0,0 +1,41 @@
# Python provides built-in JSON libraries to encode and decode JSON.
# In Python 2.5, the simplejson module is used, whereas in Python 2.7, the json module is used. Since this interpreter uses Python 2.7, we'll be using json.
# In order to use the json module, it must first be imported:
import json
# To load JSON back to a data structure, use the "loads" method. This method takes a string and turns it back into the json object datastructure:
# To encode a data structure to JSON, use the "dumps" method. This method takes an object and returns a String:
json_string = json.dumps([1, 2, 3, "a", "b", "c"])
print(json.loads(json_string))
print(json_string)
# Python supports a Python proprietary data serialization method called pickle (and a faster alternative called cPickle).
# You can use it exactly the same way.
import pickle
pickled_string = pickle.dumps([1, 2, 3, "a", "b", "c"])
print(pickle.loads(pickled_string))
# The aim of this exercise is to print out the JSON string with key-value pair "Me" : 800 added to it.
import json
# fix this function, so it adds the given name
# and salary pair to salaries_json, and return it
def add_employee(salaries_json, name, salary):
# Add your code here
salaries = json.loads(salaries_json)
salaries[name] = salary
return json.dumps(salaries)
# test code
salaries = '{"Alfred" : 300, "Jane" : 400 }'
new_salaries = add_employee(salaries, "Me", 800)
decoded_salaries = json.loads(new_salaries)
print(decoded_salaries["Alfred"])
print(decoded_salaries["Jane"])
print(decoded_salaries["Me"])

View File