Industrial software is often so big that it doesn't all fit on one page,
so people have to break it up into chunks just like a book is broken up into chapters
or the body of human knowledge is broken up into many books.
In computer science, a module is a repository or a library of code--
functions and data that do useful things.
In Python, import brings in a module.
It turns out that there is already a bunch of functions
related to regular expressions. We won't have to reinvent the wheel.
We can just import them into our own Python programs and get their benefits for free.
Python's regular expression module is called, imaginatively enough, "re"--regular expressions.
At the beginning of a Python program, just write "import space re"
and then you'll have access to all of the regular expression functions.
I'm going to show them to you in just a minute.
If we're going to write down regular expressions in Python, we need to know what they look like.
Python regular expressions look just like strings.
They start with double quotes or single quotes, and they have contents,
except that to separate regular expressions from strings
regular expressions begin with a lowercase "r" outside of the double quotes.
Up here this is a--zero, one, two, three, four--a five-character string 0 through 9.
This one down here that begins with an "r" is a regular expression
that matches 10 different one-letter strings.
Writing regular expressions is a creative process.
You the programmer have to do it.
I'm using "creative" here in the same way that people often describe mathematics as elegant.
Just as there are many different equations that could get you the number 4--
2 plus 2, 1 plus 3, 8 divided by 2, absolute value of the square root of 16--
in fact, and infinite number--there are often an infinite number of regular expressions
that could serve a purpose.
Picking the right one, the small one, the simple one, the concise one, the elegant one,
requires creativity. It's a skill. It's something you'll learn in this class.
Let's say you've written a regular expression, though--like this one.
Now we need to use it.
One of the most common functions involving regular expressions is findall.
It takes a regular expression and a string and returns a list of all of the substrings
that match that regular expression.
Here if we're looking for single letter strings that are between 0 and 9,
the 1 matches, the plus does not, the 2 matches, the equals does not,
the equals does not, and the 3 matches.
The return value of re.findall
is a list--1, 2, 3--of all of the substrings that match the regular expression.
The list could be empty if you didn't actually match anything.
This "re" means it comes from the regular expression library.
We really need that import statement at the beginning for this to work.
In this example, I'm using the same haystack string--"1+2==3"--
but I'm using a different regular expression.
This one only matches two single-letter strings.
We'll get out 1 and 2. These two match. The 3 does not, because it's not between 1 and 2.
It's not specified or matched by this regular expression.
This last example is a little more tricky.
We're looking for the letters a through c,
but if you look carefully, these are the lowercase letters a and c.
So even though this "B" is very tempting--this capital "B" in "Barbara,"
it's not between lowercase a and lowercase c.
We'll match this a, b, a, a, and then there's nothing over here in "Liskov."
Barbara Liskov is a well-known computer scientist, famous for her work in
object-oriented programming and systems programming.
Among other things she invented the language Clu,
which I'm showing here with a bit of a magnifying lens.
She received the Turing Award--the highest honor is computer science.
I programmi professionali sono spesso talmente complessi che non entrano in un'unica pagina,
così vengono divisi in frammenti, come un libro in capitoli
o il corpo della conoscenza umana è diviso in molti libri.
In informatica, un modulo è un contenitore (repository) o una libreria --
metodi e dati che fanno cose utili.
In Python il metodo "import" carica un modulo.
Scopriamo che ci sono già molti metodi già pronti
che riguardano le espressioni regolari. Non dovremo reinventare la ruota.
Possiamo semplicemente importare la libreria nel nostro programma e beneficiarne senza fatica.
Il modulo per le espressioni regolari in Python è chiamato, non senza immaginazione, "re" -- regular expressions.
All'inizio del programma, basta scrivere "import" spazio "re"
per avere accesso a tutte i metodi relativi alle espressioni regolari.
Ve le mostrerò tra un minuto.
Se dobbiamo scrivere espressioni regolari in Python, dobbiamo sapere come si presentano.
Le espressioni regolari in Python sono stringhe.
Comincia per apice singolo o doppio apice, ed hanno dei contenuti,
soltanto che, per distinguerle dalle normali stringhe,
le espressioni regolari cominciano con una "r" minuscola appena prima degli apici della stringa.
Qui abbiamo 1, 2, 3, 4, 5 --- una stringa da cinque caratteri da 0 a 9.
Questa invece comincia con "r" ed è una espressione regolare
che corrisponde dieci differenti stringhe formate da un carattere.
Scrivere espressioni regolari è un processo creativo.
Tu, programmatore devi fare questo sforzo creativo.
Sto usando qui l'aggettivo "creativo" come spesso si usa il termine "elegante" per descrivere espressioni matematiche.
Proprio come ci sono molte equazioni che danno come risultato il numero 4 ---
2 più 2, 1 più 3, 8 diviso 2, o valore assoluto di radice di sedici --
praticamente un'infinità -- ci sono spesso infinite espressioni regolari
che possono ottenere il risultato sperato.
Scegliere quella giusta, la più breve, la più semplice, quella concisa, quella elegante
richiede creatività. E' una capacità che imparerete nel corso delle lezioni.
Diciamo che avete scritto una espressione regolare infine --- come questa.
Ora dobbiamo utilizzarla.
Uno dei metodi più usati per le espressioni regolari è findall()
Accetta come parametri una espressione regolare ed una stringa, e ritorna una lista di tutte le sottostringhe
che corrispondono con l'espressione regolare.
Adesso, se cerchiamo una stringa di un carattere che è una cifra tra 0 e 9,
'1' corrisponde, il '+' non corrisponde, '2' corrisponde, '=' non corrisponde,
'=' non corrisponde, invece il '3' sì.
re.findall() ritornerà una lista
--- [1, 2, 3] --- di tutte le sottostringhe che corrispondono con l'espressione regolare.
La lista potrebbe essere vuota se non si trovano corrispondenze.
Questo "re" è la libreria Python dedicata alle espressioni regolari.
Abbiamo proprio necessità del comando "import" all'inizio del nostro programma.
Nell'esempio seguente userò la stessa stringa di partenza: '1 + 2 == 3' ---
ma userò una differente espressione regolare.
Questa in particolare corrisponde solo due stringhe contenenti un carattere.
Vedremo come '1' e '2' corrispondono. Il '3' no! Poiché non è compreso tra 1 e 2.
Non corrisponde a questa specifica espressione.
L'ultimo esempio è un po' più insidioso.
Cerchiamo le lettere tra "a" e "c",
ma se guardate attentamente, queste sono le minuscole tra "a" e "c".
Quindi questa "B" ci tenta --- la lettera maiuscola in 'Barbara',
ma non è tra "a" e "c" minuscole.
Troveranno corrispondenza 'a', 'b', 'a', 'a' e niente altro qui in 'Liskov'.
Barbara Liskov è uno scienziato informatico molto conosciuto, famosa per il suo lavoro
con la programmazioni ad oggetti e la programmazione di sistemi.
Tra l'altro ha inventato il linguaggio "Clu",
che vi mostro qui attraverso la lente d'ingrandimento.
Ricevette il Turing Award -- la più alta onorificenza in campo informatico.
産業用ソフトウェアは大きすぎて
1ページに収まらないことが多いです
したがって本が章に分けられているように
作り手はいくつかのまとまりに
区切る必要があります
モジュールとは
コードの保管場所またはライブラリのことで
コードとは
有益なことを実行する関数やデータのことです
Pythonではimport文を使って
モジュールを取り入れます
すでに正規表現に関する関数の集まりがあるので
新たに発明する必要はありません
自身のPythonプログラムにインポートして
それらの機能を自由に使えるのです
Pythonの正規表現モジュールは
Regular Expressionの頭文字を取って
reと呼ばれています
Pythonプログラムの初めに“import re”と
書くだけです
これで正規表現関数のすべてに
アクセスすることができます
ではこのあとすぐにお見せします
Pythonの正規表現を書くならば
それがどう見えるのか知る必要があります
Pythonの正規表現は文字列のように見えます
ダブルもしくはシングルクォーテーションで始まり
そこに内容を表示します
文字列と正規表現を分けるために
正規表現は小文字のrから始まり
このrをダブルクォーテーションの外に置きます
上のこれは0、1、2… 5文字の文字列です
下のrから始まるこれは正規表現です
こちらには10種類の1文字の文字列が一致します
正規表現を書くことはクリエイティブな作業です
プログラマにはこの作業が必須です
数学は“エレガント”なので
それに対抗して“クリエイティブ”と言っています
例えば答えが4になる数式はいくつも存在します
2+2、1+3、8/2、16の平方根の絶対値など
いくらでもあります
これと同様に ある役割を果たす正規表現の数は
無限にあると言えます
正しいもの、小さいもの
エレガントなものなどを選ぶことは
創造性を必要とします
このスキルをこのクラスで学びます
では皆さんがこのような正規表現を書いたとして
それを使う方法を見ていきましょう
正規表現に関する一般的な関数の一つに
findallがあります
これは正規表現と文字列を受け取り
正規表現に一致する部分文字列の
すべてのリストを返します
0から9の間にある1桁の文字列を探してみると
1は一致しますが+は一致しません
2は一致し =は一致しない
=は一致せず 3は一致します
re.findall関数の戻り値 は
1、2、3のような正規表現に一致する
すべての部分文字列リストです
何も一致しなければリストは空になります
このreは正規表現ライブラリからきている
ことを意味します
作業の始めにこのimport文が必要です
この例でも1+2==3と
同じ対象文字列を使っていますが
使っている正規表現は異なります
これは2種類の1桁の文字列だけに一致します
1と2を取り出すとこの2つが合致するので
[‘1’,‘2’]を得ます
この正規表現で指定された範囲にないので
一致しません
最後の例はもう少し複雑です
aからcの文字を探しています
よく見るとこれらは小文字のaとcです
Bも一致しそうですがこれは
Barbara内の大文字のBです
小文字のaとcの間の文字ではありません
一致するのはこのa、b、a、aです
Liskovの中に一致するものはありません
バーバラ・リスコフは
コンピュータ・サイエンティストとして知られ
オブジェクト指向プログラミングと
システムプログラミングで有名です
その他にも彼女はCLU言語を発明しました
虫眼鏡で探すのは手がかり(clue)で
CLUじゃありませんね ジョークですよ
彼女はコンピュータ・サイエンスの最高栄誉である
チューリング賞を受賞しました
Sistemas de software são em geral muito grandes e não cabem em uma página,
por isso, são divididos em módulos, assim como livros são divididos em capítulos,
ou como o conhecimento sobre o corpo humano é dividido em vários livros.
Em computação, um módulo é um repositório ou uma biblioteca de código --
funções e dados para tarefas úteis.
Em Python, a diretiva import serve para importar um módulo.
Existem várias funções prédefinidas
relacionadas a expressões regulares. Não precisamos reinventar a roda.
Podemos simplesmente importar essas funções em nossos programas e usá-las livremente.
O módulo Python para expressões regulares é chamado "re" -- expressões regulares.
No início de um programa Python, escreva simplesmente "import re"
para ter acesso a todas as funções disponíveis para manipular expressões regulares.
Vou mostrar algumas delas daqui a pouco.
Se vamos escrever expressões regulares em Python, precisamos conhecer a sua forma.
Expressões regulares em Python são como strings.
Elas começam e terminam com aspas simples ou duplas, e têm um conteúdo.
Para distinguir expressões regulares de strings,
expressões regulares começam com a letra minúscula "r", antes das aspas duplas.
Isto aqui é um string com cinco caracteres "[0-9]".
Isto aqui, começando com um "r", é uma expressão regular
que casa com 10 diferentes strings com apenas um dígito.
Escrever expressões regulares é um processo criativo.
Você, como programador, é que tem que fazer isso.
Digo criativo no mesmo sentido em que se diz muitas vezes que matemática é elegante.
Assim como existem muitas diferentes equações que denotam o número 4 --
2+2, 1+3, 8/2, abs(sqrt(16)) --
de fato, um número infinito de tais equações -- existe frequentemente um número infinito de expressões regulares
que servem a um determinado propósito.
Escolher a mais apropriada -- mais concisa, mais simples, mais elegante --
requer criatividade. É uma habilidade que você vai adquirir neste curso.
Digamos que você escreveu uma expressão regular, por exemplo, esta aqui.
Agora você quer usá-la.
Uma das funções mais comuns sobre expressões regulares á findall.
Ela tem como argumentos uma expressão regular e um string e retorna a lista de todos os substrings
que casam com a expressão regular.
Aqui, estamos procurando por strings de um caractere, entre "0" e "9":
o "1" casa, o "+" não casa, o "2" casa, "=" não casa,
o "=" não casa e o "3" casa.
O valor retornado por re.findall
é a lista ["1", "2", "3"] -- que contém todos os substrings que casam com a expressão regular.
A lista pode ser vazia, se a expressão regular não casa com nenhum sbstring.
"re" aqui significa a função é da biblioteca relativa a expressões regulares
Precisamos incluir "import re" no início do programa.
Neste exemplo, o string é novamente "1+2==3",
mas estou usando agora outra expressão regular.
Esta aqui casa apenas com dois strings de um caractere.
Obtemos "1"e "2"-- esses dois casam. O "3" não casa porque não está entre 1 e 2.
"3" não é especificado, ou não casa, com esta expressão regular.
O último exemplo á mais complicado.
Procuramos pos letras de "a" a "c",
mas se você observar, essas letras são minúsculas.
Portanto, "B" maiúsculo, em "Barabara",
não está entre "a" e "c".
A expressão casa com "a", "b", "a", "a" e nenhum caractere em "Liskov".
Barbara Liskov é uma cientista famosa em computação, pelo seu trabalho em
programação orientada a objetos e programação de sistemas.
Entre outras coisa, ela projetou a linguagem CLU.
que eu estou representando aqui.
Ela recebou o Turing Award -- o maior prêmio em ciência da computação.
工业软件通常都是很大的,不适合于放在一个页面上
所以人们必须将其分成各个模块,就好像将一本书分成多个章节
或者将关于人体的知识划分为多本书籍那样
在计算机科学领域,模块是指代码的仓库--
用来做有用的事情的函数和数据
在Python里,模块是导入的
原来就已经有一堆关于正则表达式的函数
我们就没必要重新发明轮子咯
我们只需要将其导入到我们自己的Python程序里,就能免费获得其功能
想下就知道,Python的正则表达式模块“re”,就是regular expressions
在Python程序的开始部分,只要写“import re"就行了
那你就能访问所有的正则表达式函数了
等下我就展示给你们看
如果我们将要在Python里编写正则表达式,我们需要知道它们看起来是怎样的
Python正则表达式看起来很像字符串
它们以双引号或单引号开头,包含文字
为将正则表达式与字符串作区分
正则表达式在双引号的外面,以小写的”r“开头
这里,0,1,2,3,4 有5个字符串,0到9
这里以”r“开头,是一个正则表达式
匹配10个不同的单字母字符串
编写正则表达式,是一个创意过程
作为程序员必须要做这个
这里我用了”创意“这个词,跟人们通常将数学描述成优雅是一个意思
正如有很多不同的数学等式能够得出4一样
2加2,1加3,8除以2,16的平方根的绝对值 ---
实际上,有无数个等式会得到这个结果 -- 通常也是有无数种
正则表达式的结果是一样的
挑选出一个正确、小型、简单、简洁、优雅的正则表达式
需要”创意“。这是一种技巧,是你在本堂课将要学到的。
假如你已经写下了一个正则表达式 -- 像这个
现在我们需要使用它
涉及到正则表达式,最常用的一个方法是findall
它接收一个正则表达式和一个字符串,并返回包含所有匹配
那个正则表达式的子字符串的列表
这里假如我们在查找0到9之间的单字母字符串
那么1匹配,加号不匹配,2匹配,等号不匹配
等号不匹配,3匹配
re.findall返回的值
是一个列表 -- 1,2,3 -- 所有匹配该正则表达式的子字符串
如果不匹配任何东西,列表就可能是空的
这个”re“表示它来自于正则表达式库
为了使其能起作用,我们必须在程序的开头部分写下import语句
在这个例子里,我用同样的字符串 ”1+2==3“
但使用不同的正则表达式
这个只匹配两个单字母字符串
我们将得到1和2。就这两个匹配。3不匹配,因为它不在1和2之间
它不被这个正则表达式指定或匹配
最后这个例子有点棘手
我们在查找a到c之间的字母
但如果你认真看,这些是小写a到c之间的字母
所以即使”B“很吸引人 -- ”Barbara“首字母”B“
并不在小写a到小写c之间
我们将匹配这个a,b,a,a,而在”Liskov“里就没有匹配的
Barbara Liskov是一个知名的计算机科学家
因其在面向对象编程和系统编程方面的工作而出名
此外,她还发明了编程语言Clu
就是我用放大镜显示的地方
她获得了图灵奖--计算机科学领域最高的荣誉