Introduction to Python - Part 2

[Pages:17]Introduction to Python Part 2

COMPSCI 260 1 September 2014

Part 2 Topics:

? Regular expressions (and the re package) ? Python code reuse, modules, and import ? File I/O ? range() function ? Multidimensional arrays ? Some useful Python modules ? Quick note on debugging ? Other resources

Regular Expressions (Regex)

? Useful for finding matches to patterned

strings.

?

Regular Expressions in Python

? Make sure you import the module "re".

Method

Purpose

sub() search()

match() findall() finditer()

Search and replace the matched substring with a new string

Scan through a string, looking for any location where this RE matches.

Determine if the RE matches at the beginning of the string.

Find all substrings where the RE matches, and returns them as a list.

Find all substrings where the RE matches, and returns them as an iterator.

Regular Expressions in Python

?MatchObject methods (used with match or

search).

Python 2.7 Regular [5b-d] matches any chars '5', 'b', 'c' or 'd'

[^a-c6] matches any char except 'a', 'b', 'c' or '6'

R|S ()

Expressions matches either regex R or regex S.

Creates a capture group, and indicates precedence.

SWpitehCciniaol[mc]h,manraoocntseprRes:ceiagl echxarSs ydmo abnoytlhsing special, hence

they don't need escaping, except for ']' and '-', w\.hich onemlsayctacnpheeessedsapneeycsiccahalarpcainhcatgrearicfttehres.y are not the 1st char. e^.g. '[]ma]t'chesmsatatcrht eosf t'he]'st.ri'ng^'(or alilsnoe ifhaMsULTsILpIeNcE)ial

m$eaningm, aittcnheesgaetnedsofthtehegrsoturpingif (ito'sr tlhienefiirfstMcUhLTaIrLaIcNtEe)r in

[5b-d] matches any chars '5', 'b', 'c' or 'd'

th[e^a[-c]6,]amnadtcnheesedansytochbare eexscceaptpe'da't,o 'mb'a,tc'hc'itolrite'r6a'lly.

R|S

matches either regex R or regex S.

Q(u)antifieCrrse:ates a capture group, and indicates precedence.

W*ithin []0, onromsopreecia(lacphpeanrds ?dofoarnnyothn-inggreesdpye)cial, hence th+?ey don10't oonrrem1eodreesca""ping, except for ']' and '-', w{hmi}ch onelyxancteleyd'em'scaping if they are not the 1st char. e{{.gmm,,. nn}}'?[]ff]rr'oomm mmmttaootcnnh.,e'asms'f'de]ew'faa.usl'tpso^s'tsoib0la,els'on' htaosinsfpineictiyal meaning, it negates the group if it's the first character in

the [], and needs to be escaped to match it literally.

Practice Time:

? Use 10 minutes to play with Part5.py from

Tutorial Part 2 in Eclipse.

Import

? You can make use of any Python module or

your own code libraries with import.

? import module_name

o import re

# usually at top of python script

o You'll have to invoke using re.findall()

? from module_name import function_name

o from re import * # * means import all functions o Can invoke module functions like findall() directly

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download