#代码实现:
#coding = utf-8
import re
pattern = re.compile(r"[a-zA-Z]+")
count = 0
with open("e:\\python\\1129\\a.txt","r") as fp:
for line in fp:
s=[]
if pattern.findall(line):
print(pattern.findall(line))
s=pattern.findall(line)
count+=len(s)
print(count)
输出结果:
E:\python\1130>python 5.py
['Word']
['I', 'am', 'murphy']
['and', 'you']
['hi']
['murphy']
8
另外一个例子:写一个函数,其中用正则验证密码的强度
#coding = utf-8
import re
password = input("请输入6位密码:")
pattern =re.compile(r"\d+|\w+|\d+\w+|\w+\[!@#$%^&*]+")
check_password=pattern.findall(password)
if check_password:
for i in check_password:
if i.isdigit():
print("密码强度:弱",str(check_password))
elif i.isalpha():
print("密码强度:中",str(check_password))
elif i.isalnum():
print("密码强度:强",str(check_password))
输出结果:
E:\python\1130>python 6.py
请输入6位密码,退出请输入q:123456
密码强度:弱 ['123456']