1.編寫驗證email的正則表達式,郵箱名可以是英文字母或數字或-,_符號,郵箱后綴網址名可以是字母或數字,域名可以是com、org、edu
例如: 1111Hugo_@lester007.com即為合法的email地址
(1)match()
方法判斷是否匹配,如果匹配成功,返回一個Match
對象,否則返回None
。常見的判斷方法就是:
test = '用戶輸入的字符串' if re.match(r'正則表達式', test): print('ok') else: print('failed')
#!usr/bin/dev python #coding:utf-8 import re email = '1111Hugo_@lester007.com' f = re.match(r'()@().(com|edu|org)',email) print f
這是首先我想到的代碼,然后匹配用戶名
f = re.match(r'(\w+[-\w*]*)@([\w]*).(com|edu|org)',email)
#預定義字符集,可以寫在[...]中
\d 代表[0-9], a\dc a1c
\D 非數字, a\Dc abc
\s 空格, a\sc a c
\S 非空字符 a\Sc aSc
\w 單詞字符[a-zA-Z0-9] a\wc a1c,aec,aXc都可以匹配到
\W 非單詞字符 a\Wc a c,a#c,a^c 就可以匹配到了
#數量詞,可以用在字符或(...)之后。
* 匹配前一個字符0或無限次
+ 匹配前一個字符1或無限次
? 0或1次
{m} 匹配前一個字符m次 ab{2}c abbc 與預定義字符集結合起來比如 f=re.findall(r'(\w+\s+)',str)就可以找到非行首的多個空格了
{m,n} 匹配一個字符m至n次,at{3,4}c 就會匹配到 atttc和attttc ,而不會匹配到atc 或者 atttttc
| 代表表達式兩側的任意匹配一個
2.利用隨機函數產生一個用戶的用戶名密碼,並利用文件將用戶名和密碼保存下來。
用戶名一般是8-32位的,允許包含下划線,密碼通常是8-16位,允許包含特殊字符
#!usr/bin/dev pyhton #coding:utf-8 import random import hashlib runum = random.randint(8,32) print runum us = 0 usrname = '' for us in range(runum): us+= 1 rs = random.choice('qwertyuiopasdfghjklzxcvbnm1234567890_') usrname += rs print usrname pword = '' rpnum = random.randint(8,16) ps = 0 for ps in range(rpnum): ps += 1 pw = random.choice('qwertyuiopasdfghjklzxcvbnm1234567890!@#$%^&*()-=[]\\|}{;:""?><,.\'`~') pword += pw print pword
3.密碼沒有加密,將密碼使用md5庫處理,並保存。
md5加密處理庫
import hashlib
hashlib.md5(password).hexdigest()
上面已經寫了,如何生成隨機用戶名和密碼,就不重新寫了,只寫如何保存md5.
import hashlib
md5pword = hashlib.md5(pword).hexdigest() print md5pword with open('usrmd5p.txt','w') as f: f.write(usrname) f.write('\n') f.write(pword) f.write('\n') f.write(md5pword) f.close()
4.文本處理
上個月做了一家做自然語言的公司的筆試題,我覺得題目還是有點意思的,要求如下:
-
去除所有標點符號;需要去除的標點符號是如下幾種: , . ! ? : ;
-
所有數字包括小數,整數,負數都替換成一個替代字符串: ==NUMBER==
-
所有大寫字母全部轉成小寫
-
去除每行起始的所有空格
-
連續的空格縮短為單獨的空格(除每行起始連續空格,見以上規則4)
-
如果經過上述處理導致一行為空,則在此行處放置標記字符串:[REMOVED]
文本有點長,我放在網盤上了:https://pan.baidu.com/s/1o8mdXd4
#!usr/bin/dev python #coding:utf-8 import os import re def stre(s): s = re.sub(r'(^\ +)','',s) s = re.sub(r'(\ +)',' ',s) s = re.sub(r'([,+.+!+?+:+;+])','',s) s = re.sub(r'(\d+)','==NUMBER==',s) if s == '': s = '[REMOVED]' elif s == None: s = '[REMOVED]' s = s.lower() with open('test_output.txt','a+') as fw: fw.write(s) with open('test_input.txt','r') as fr: for line in fr: stre(line)
#這是我用正則表達式進行處理的。