Salta al contenuto
Note per Studenti Python Notebooks - Strings and Regular Expressions Report

Python Notebooks - Strings and Regular Expressions

In questa pagina 6

Part of the Python section of the course (data cleaning, "nuts and bolts" of the objectives in Introduction to Machine Learning - Learning, Data and TasksMachine learning builds a hypothesis g that approximates an unknown target function f using only a set of historical examples (input, output). The course lecture frames learning as adaptive behaviour, shows through the credit-approval example the components of learning (input x, output y, target f, data, hypothesis g, hypothesis set, learning algorithm) and warns that a model is only as unbiased as its data. Tasks named in the course are classification and regression, supervised and non-supervised problems.Introduction to Machine Learning - Learning, Data and Tasks →). The language basics are in Python - BasicsPython 3 is a high-level, general-purpose, interpreted language. A program is a sequence of statements run by the interpreter, either interactively at the prompt or from a file with the edit/run loop. Variables are names bound to values by assignment; the basic types are int, float, str and bool, with explicit conversions (int, float, str, bool) and input always returning a string. Arithmetic uses the operators plus, minus, star, slash, double slash, percent and double star with precedence rules, relational operators produce booleans, and and, or, not combine them (precedence not, and, or; De Morgan's laws).Python - Basics → and Python - Control Flow, Lists, Functions and FilesA program makes decisions with if, elif and else, whose blocks are defined by the colon and by four-space indentation (an IndentationError otherwise). It repeats statements with while loops (condition, counter, update; infinite loops and sentinel loops) and for loops over range or over a sequence. A list is an ordered mutable container with zero-based indices, len, append, insert, pop, remove, the in operator, slicing, and sorted versus sort. Functions are defined with def, take parameters, return values with return (print is not return; no return gives None), have local variables, must be defined before being called and can live in separate modules imported with import. Text files are opened with the with statement in modes r, w or a with utf-8 encoding and read as strings.Python - Control Flow, Lists, Functions and Files →. In the copies of the notebooks available for these notes the outputs are missing; the results below are computed here by reading each call.

1. Creating strings

python
x = 'a string'
y = "a string"

x == y

Single and double quotes create the same string, so the comparison is True. A triple-quoted string can span several lines:

python
multiline = """
one
two
three
"""

multiline

The value contains the line breaks (shown as \n).

2. Case methods

python
fox = "tHe qUICk bROWn fOx."

fox.upper()        # all capitals
fox.lower()        # all lower case
fox.title()        # first letter of every word in capital
fox.capitalize()   # only the first letter of the string in capital, the rest in lower case
fox.swapcase()     # exchanges lower and upper case

Methods return a new string; the original fox is unchanged (the comments are added here).

3. Removing characters at the ends

python
line = ' this is the content '

line.strip()

strip() removes the white space at the beginning and at the end. With an argument it removes the given characters from the ends:

python
x = "write something "
y = "write something"

x == y

x.strip("g")

y.strip("g")

x == y is False (the trailing space). x.strip("g") does not change x, since x ends with a space and strip("g") removes only g characters from the ends; y.strip("g") removes the final g of "something".

4. Searching and replacing

python
line = 'the quick brown fox jumped over a lazy dog'

line.find('foxes')

line.endswith('dog')

line.startswith('the')

line.replace("brown", "black")

find returns the index where the substring starts, or −1-1 if it is not there (here 'foxes' is not found, so −1-1); endswith and startswith return True or False (both True here); replace returns the string with every occurrence replaced.

python
line = 'the quick brown fox jumped over a lazy dog, the lazy dog is scared'

line.replace("dog", "cat")

line.replace("dogs", "cat", 3)

The first call replaces both occurrences of dog; the second searches dogs, which does not appear, so nothing changes (the third argument is the maximum number of replacements).

python
parts = line.partition('fox2')

parts

partition splits at the first occurrence of the separator and returns a tuple (before, separator, after); if the separator is not found (as with 'fox2') it returns the whole string followed by two empty strings.

5. Splitting

python
line.split()

line.split(maxsplit = 4)

split() cuts at white space and returns a list of words; with maxsplit = 4 at most four cuts are made and the rest of the string stays in the last element.

python
haiku = """matsushima-ya
aah matsushima-ya
matsushima-ya"""

haiku

haiku.splitlines()

haiku.split("\n")

splitlines() and split("\n") both return the list of the three lines.

6. Regular expressions

python
import re

txt = "The rain in Spain"

x = re.search("^The.*Spain$", txt)

x

re.search(pattern, text) looks for the pattern anywhere in the text and returns a match object (or None). In the pattern: the caret ^ is the start of the string, the dollar sign at the end of the pattern is the end of the string, . any character, * zero or more repetitions of the previous element. So the pattern of the cell (caret, The, .*, Spain, dollar sign) matches a string that starts with The and ends with Spain: here it matches.

Further searches in the notebook (each applied to txt):

python
re.search("rain", txt)          # found in the middle of the string

re.search("pain$", txt)         # the text ends with "pain": found

re.search(".a.n$", txt)         # any char, a, any char, n at the end: "pain"

re.search(".*", txt)            # matches the whole string

re.search(".*spain", txt)       # lower case "spain" is not in the text: no match (None)

re.search(".*pain", txt)        # from the start up to "pain"

re.search(".* in", txt)         # as much text as possible ending with " in"

re.search("[a-m]in", txt)       # a letter between a and m followed by "in"

re.findall("[a-m]in", txt)      # all the non-overlapping occurrences, as a list

re.findall(".a", txt)           # all the pairs: any character followed by "a"

The square brackets define a character class; re.findall returns the list of all the matches (the comments are added here; the cells show only the calls).

Cleaning a string with re.sub(pattern, replacement, text):

python
line = ' this is the content '

line.strip()

re.sub(" +", " ", line)

re.sub("^ +| +$", "", line)

" +" is one or more spaces, replaced by a single space; the second pattern is spaces at the start (after the caret) or (| means "or") spaces at the end (before the dollar sign), replaced by nothing: the same result as strip().

Versione ripasso

Python Notebooks - Strings and Regular Expressions

  • Quotes: '...' and "..." are the same; """...""" spans lines.
  • Case methods return a new string: upper(), lower(), title() (each word), capitalize() (first letter), swapcase().
  • strip() removes white space at the ends; strip("g") removes the given characters at the ends.
  • Search: find(sub) gives the index or -1; startswith, endswith give True/False; replace(old, new, count); partition(sep) gives (before, separator, after), or the whole string and two empty strings if the separator is missing.
  • Splitting: split() into words; split(maxsplit=4) at most four cuts; splitlines() and split("\n") for lines.
  • Line breaks: a triple-quoted haiku of three lines gives three elements with splitlines() and with split("\n").
  • Regular expressions (import re): re.search(p, t) first match or None; re.findall(p, t) list of all matches; re.sub(p, r, t) replacement.
  • Pattern pieces: caret = start of string; dollar sign = end of string; . any character; * zero or more; + one or more; [a-m] a class; | "or".
  • Example "The rain in Spain": a pattern starting with caret and ending with Spain matches; ".*spain" gives no match (lower case).
  • Cleaning: re.sub(" +", " ", line) collapses spaces; removing spaces at both ends gives the same result as strip().
  • Typical errors: expecting strip or replace to modify the string in place; case-sensitive search; .* is greedy; reading -1 as an error.

Teoria collegata