有如下数据:筛选出不合格密码的用户,对出现至少四个连续数值为不合格密码,例如"1234"、"8765"为不合格密码
用户名 | 密码 |
---|---|
X | 12345678 |
Y | 87654321 |
O | 10293847 |
P | 39485726 |
Q | 28475639 |
R | 19283746 |
S | 91827364 |
T | 56473829 |
U | 83746592 |
V | 28374659 |
W | 74839201 |
A1 | 12093847 |
B1 | 90817263 |
C1 | 475876510 |
最终结果:
用户名 | 密码 |
---|---|
X | 12345678 |
Y | 87654321 |
C1 | 475876530 |
解决办法:
第一种解决办法:
import pandas as pd
import re
# 样本数据
data = {
"用户名": ["X", "Y", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "A1", "B1", "C1"],
"密码": ["12345678", "87654321", "10293847", "39485726", "28475639", "19283746", "91827364",
"56473829", "83746592", "28374659", "74839201", "12093847", "90817263", "475876530"]
}
# 创建DataFrame
df = pd.DataFrame(data)
# 检查密码是否包含至少四个连续的递增或递减数值
def check_invalid_password(password):
# 正则表达式匹配4个或更多的连续递增数字
increasing_pattern = r'0123|1234|2345|3456|4567|5678|6789'
# 正则表达式匹配4个或更多的连续递减数字
decreasing_pattern = r'9876|8765|7654|6543|5432|4321|3210'
# 检查密码是否符合递增或递减的条件
if re.search(increasing_pattern, password) or re.search(decreasing_pattern, password):
return True
return False
# 过滤出不合格密码的用户
invalid_passwords = df[df['密码'].apply(check_invalid_password)]
# 输出不合格的密码
print(invalid_passwords)
第二种:
import pandas as pd
import re
# 样本数据
data = {
"用户名": ["X", "Y", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "A1", "B1", "C1"],
"密码": ["12345678", "87654321", "10293847", "39485726", "28475639", "19283746", "91827364",
"56473829", "83746592", "28374659", "74839201", "12093847", "90817263", "475876540"]
}
# 创建DataFrame
df = pd.DataFrame(data)
#定义了一个名为 check_invalid_password 的函数,该函数接受一个名为 password 的参数。这个函数的作用是检查给定的 password 字符串是否包含至少四个连续的递增或递减数字。
#如果包含,则返回 True,否则返回 False。
def check_invalid_password(password):
"""
检查密码是否包含至少四个连续的递增或递减数值。
Args:
password (str): 要检查的密码。
Returns:
bool: 如果密码包含至少四个连续的递增或递减数值,则返回 True,否则返回 False。
"""
for i in range(len(password) - 3):
# 检查递增序列
if ord(password[i]) + 1 == ord(password[i+1]) == ord(password[i+2]) - 1 == ord(password[i+3]) - 2:
return True
# 检查递减序列
if ord(password[i]) - 1 == ord(password[i+1]) == ord(password[i+2]) + 1 == ord(password[i+3]) + 2:
return True
return False
# 过滤出不合格密码的用户
invalid_passwords = df[df['密码'].apply(check_invalid_password)]
# 输出不合格的密码
print(invalid_passwords)
最终输出结果