Python核心程式設計第三版——第一章練習題答案
1.6 練習
正則表示式
1-1 [bh][aiu]t;
1-2 \w+ \w+;
1-3 \w+,\s\w+;
1-4 [A-Za-z_]+[\w_]+
python有效識別符號的定義:
1.python中的識別符號是區分大小寫的。
2.標示符以字母或下劃線開頭,可包括字母,下劃線和數字。
3.以下劃線開頭的識別符號是有特殊意義的。
1-5 \d+(\s\w+)+
1-6 (1)^w{3}://.+com/?$ (2)^\w+://.+?\.\w{3}/?$
1-7 [\+-]?\d+
1-8 [\+-]?\d+[lL] (注:python3已經把int和長整數合併了,沒有123L這種表示法了)
1-9 [\+-]?\d*\.\d* (注: 此處用*是因為 .1 表示 0.1,1. 表示 1.0)
1-10 ([\+-]?\d*(\.\d*)?){2}i?
1-11 \w+[\w_-\.]*\[email protected]\w+\.\w{2,3}
電子郵件表示:使用者名稱[email protected] +郵箱域名.com/org/cn...
有效電子郵件地址:使用者名稱,可以自己選擇。由字母、數字、點、減號或下劃線組成。只能以數字或字母開頭和結尾。
1-12 https?://[\w_\.-]*\w+/? (並不知道所謂的有效URL是什麼規則,這答案也不知道是否能全匹配成功)
1-13 \s'(.+)'
1-14 1[0-2]
1-15
(1)\d{4}-(\d+)-(\d+)(?:-(\d{4}))?
(2)
def check(card): contexts = re.search(r'\d{4}-(\d+)-(\d+)(?:-(\d{4}))?', card).groups() if not contexts[2] and len(contexts[0]) == 6 and len(contexts[1]) == 5: return True elif contexts[2] and len(contexts[0]) == 4 and len(contexts[1]) == 4 and len(contexts[2]) == 4: return True else: return False
使用gendata.py
1-16
from random import *
from string import ascii_lowercase as lc
from sys import *
from time import *
tlds = ('com', 'edu', 'net', 'org', 'gov')
with open('reddata.txt', 'w') as f:
for i in range(randrange(5, 11)):
dtint = randrange(maxsize)
dtstr = ctime(dtint)
llen = randrange(4, 8)
login = ''.join(choice(lc) for j in range(llen))
dlen = randrange(llen, 13)
dom = ''.join(choice(lc) for j in range(dlen))
f.write('%s::%[email protected]%s.%s::%d-%d-%d\n' % (dtstr, login, dom, choice(tlds), dtint, llen, dlen))
1-17
import re
def Count(filename):
weeks = {}
with open(filename) as f:
contexts = f.read()
result = re.findall(r'(\w{3})\s\w{3}', contexts)
for i in result:
weeks[i] = weeks.get(i, 0) + 1
return weeks
weeks = Count('reddata.txt')
print(weeks)
1-18 看了很多遍,還是無法理解這道題的意思
1-19 \w{3}\s.*?\s\d{4}
1-20 \[email protected]\w+\.\w{3}
1-21 \s(\w{3})\s
1-22 \s(\d{4})
1-23 \d{2}:\d{2}:\d{2}
1-24 (\w+)@(\w+\.\w{3})
1-25 (\w+)@(\w+)\.(\w{3})
1-26
import re
def Replace(filename, mail):
with open(filename) as f:
contexts = f.read()
replace = re.sub(r'\w*@\w*\.\w{3}', mail, contexts)
print(replace)
Replace('reddata.txt', '[email protected]')
1-27
import re
def print_time(filename):
with open(filename) as f:
contexts = f.read()
time = re.findall(r'\s(\w{3})\s(\d{2}).*?(\d{4})', contexts)
for t in time:
print(', '.join(t))
print_time('reddata.txt')
處理電話號碼
1-28 (\d{3}-)?\d{3}-\d{3}
1-29 (\()?(\d{3})?(?(1)\) |-?)\d{3}-\d{3} 簡單化:((\d{3}-)|(\(\d{3}\) ))?\d{3}-\d{3}
正則表示式應用程式
1-30、1-31、1-32 高深的題目,知識有限,暫時無法解決這些題。