☆☆ 新着記事 ☆☆

2018年5月30日水曜日

Python 正規表現(regular expression)の記述例



◇エスケープ・シーケンスの取り扱い

Pythonでは、通常の文字列では表せない文字(タブや改行など)をバックスラッシュ' \ 'をつけたエスケープシーケンス(\t\nなど)で記述する。

\t: タブ挿入
\n: 改行

WindowsだとBack Slashは '¥' の半角記号になるので、これが、Windows上のPythonで
上手く機能しているか、確認する。

(bloggerって、'ろ' の後ろは、' \ ' になるんですね。)



機能、してますね。

◇実際に使ってみる。

基本構文

import re

pattern = ("""
Jessica is 23 years old and she is an engineer of Google.
James is 33 years old and he is an employee of Ford Mortor.
Edward is 103 years old and he was born in 1900.
Alex has just bought a book of 123456 pages.
""")

ages = re.findall(r'\d{1,3}', pattern)  # search 1- 3 digit(s) number
print(ages)

names = re.findall(r'[A-Z][a-z]*', pattern) #Search words started with capital letter.
print(names)


結果

['23', '33', '103', '190', '0']

['Jessica', 'Google', 'James', 'Ford', 'Mortor', 'Edward', 'Oscar']

発展) Dictionaryへの結果の登録

import re

pattern = ("""
Jessica is 23 years old.
James is 33 years old.
Edward is 103 years old and he was born in 1900.
""")

ages = re.findall(r'\d{1,3}', pattern)  # search 1- 3 digit(s) number
print(ages)

names = re.findall(r'[A-Z][a-z]*', pattern) #Search words started with capital letter.
print(names)

x = 0
ageDict = {}
for eachName in names:
    ageDict[eachName] = ages[x]
    x+=1

print(ageDict)

['23', '33', '103', '190', '0','123', '456']
['Jessica', 'James', 'Edward']
{'Jessica': '23', 'James': '33', 'Edward': '103','Alex': '190'}
書き方解説)
Re.findall: 文字列を検索する。
   \d{1,3}
\d  : 任意の数字
{1,3 } : 1~3回の繰り返し
最大3桁の文字列として区切って検索するという意味。


正規表現の記述例:
(?P<任意の変数>[0-9]+):  任意の桁の数字を引いてくる

参考)

◇メタ文字
メタ文字説明指定例合致する
.任意の一文字
(any character,  except for new line)
a.cabc, acc, aac
^行の先頭
(Match the beginning of string)
^abcabcdef
$行の末尾
(Match the end of string)
abc$defabc
*0回以上の繰り返し
(Match 0 or more)
ab*a, ab, abb, abbb
+1回以上の繰り返し
(Match 1 or more)
ab+ab, abb, abbb
?0回または1回
(Match 0 or 1)
ab?a, ab
{m}m回の繰り返し
(range or "varaiance")
a{3}aaa
{m,n}m〜n回の繰り返し
{1,3} expecting 1-3
a{2, 4}aa, aaa, aaaa
[★]★のどれか1文字[a-c]
[a-cl-p]
a, b, c
little bother
★|★★のどれか
(either or)
a|b
nu|un
a, b
A nut for a jar of tuna.



◇特殊シーケンス(identifiers)
特殊シーケンス説明同じ意味の正規表現
\d任意の数字
(any number)
[0-9]
\D任意の数字以外
(anything but a number)
[^0-9]
\s任意の空白文字
(space)
[\t\n\r\f\v]
\S任意の空白文字以外
anything but a space
[^\t\n\r\f\v]
\w任意の英数字
any character
[a-xA-Z0-9_]
\W任意の英数字以外
anything but a character
[\a-xA-Z0-9_]
\A文字列の先頭^
\Z文字列の末尾 $



特殊シーケンス

説明

\b

任意の数字

(any number)

\n

new line

\s

space

\t

tab

\e

escape

\f

form feed

\r

return


良く使うパターン。

1)特定の文字列をどこかに含む
^(?=.*カレー).*$

’カレー'屋さんとか、 '今日、カレー食べる?' 'GoGo カレー'  などの
カレーという文字列を含む文字列がヒットする。

◇指定の箇所まで抽出(スライシング)

文字列[開始位置:終了位置:ステップ]

スライシングは開始位置は含み、終了位置は含まない。
スペースも、1インデックス分としてカウントする。

>>> s='Hello World!'
>>> s[1:5]
'ello'
>>> s[0:6:2] ♯0番目から6番目の間を2文字目毎にとってくる。
'Hlo'
>>> s[0:6:-1]
''
>>> s[::-1] ♯後ろから。
'!dlroW olleH'


 Pythonの正規表現:

import re: とか使うらしい。 別途、まとめる。

◇スペースを排除するだけなら、
文字列.strip(削除したい文字列)   で、'削除したい文字列'を省略することで
前後の余白を削除できる。

a=[
    {'area': 'ALL   ', 'original_area': 'CA ', 'number': '1?', '},
    {'area': 'ALL', 'original_area': 'CA ', 'number': '2'},
    ]
questoins=[]
for i in range(len(a)):
    area=(a[i]['area'])
    area=area.strip()
    if area =='ALL' or area =='CA':
        print(a[i])
       
で、areaの値に空白が含まれている場合でも、条件にマッチさせることができる。

◇メール・アドレスや . を削除する


Python
import re

message="
My office email address is test2018@test.com.
But my personal one is test.craig@g.co.jp.Please visit our web site @ https://test.test.com
Company information is here at https://test.test.com/about 
Sincerely, 15 Jan, 2019 "

new_message=' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)", " ", message).split())

print(new_message)


Output:
My office email address is test2018 com But my personal one is test craig co jp Please visit our web site Company information is here at Sincerely 15 Jan 2019


My office email address is test2018@test.com. But my personal one is test.craig@g.co.jp.Please visit our web site @ https://test.test.com.Company information is here at https://test.test.com/aboutSincerely,15 Jan, 2019

Python


(解説)
' '. :区切り文字をつけないで連結。
test = ['ab', 'c', 'de']
result = ''.join(test)
print(result)abcde
result2 = ','.join(test)
print(result2): ab,c,de

.split() : ()内の文字で分割する。
a = "abbaccadda"
sep = a.split("a")
print(sep) : ['', 'bb', 'cc', 'dd', '']
sep2 = a.split("ac")
print(sep2)
['abb', 'cadda']
*区切りに使用した文字列は、戻り値からは消えてしまう。

re.sub():re.sub(正規表現“置換する文字列”置換対象の文字列)
[] のどれか1文字
参考)
Pythonでエスケープシーケンスを無視(無効化)するraw文字列
https://note.nkmk.me/python-raw-string-escape/

書きながら覚えよう!Pythonで正規表現を使う方法【初心者向け】
https://techacademy.jp/magazine/15635

Python 3 Programming Tutorial - Regular Expressions / Regex with re
https://youtu.be/sZyAn2TW7GY

0 件のコメント:

コメントを投稿