【发布时间】:2021-01-01 19:40:55
【问题描述】:
我在一个名为“user_table.txt”的文本文件中有以下代表用户名和密码的数据:
Jane - valentine4Me
Billy
Billy - slick987
Billy - monica1600Dress
Jason - jason4evER
Brian - briguy987321CT
Laura - 100LauraSmith
Charlotte - beutifulGIRL!
Christoper - chrisjohn
Bruce - Bruce
然后我使用以下代码创建一个 Python 字典:
users = {}
with open("user_table.txt", 'r') as file:
for line in file:
line = line.strip()
# if there is no password
if ('-' in line) == False:
continue
# otherwise read into a dictionary
else:
key, value = line.split(' - ')
users[key] = value
k= users.keys()
print(k)
以下代码是一个使用一些简单规则进行身份验证的函数:
a) 如果用户已登录(基于 login_status),则提示
b) 如果文件中不存在用户名,则提示
c) 如果用户名存在,但与文件中的密码不匹配,则提示
这是(尝试)实现此功能的功能:
def authenticate(login_status, username, password):
with open("user_table.txt", 'r') as file:
for line in file:
line = line.strip()
# if there is no password
if ('-' in line) == False:
continue
# otherwise read into a dictionary
else:
key, value = key, value = line.split(' - ')
users[key] = value.strip()
user_table= users.items()
user_names = user_table.keys()
# print(k)
if login_status == True:
print('User {} is already logged in.'.format(username))
if username not in user_table.keys():
print('username is not found')
if username in user_table.keys() and password != user_table.get('value'):
print('the password is incorrect')
if username in user_table.keys() and password == user_table.get('value'):
print('welcome to our new application')
当我调用以下命令时:
authenticate(False, 'Brian', 'briguy987321CT')
我收到此错误:
AttributeError: 'dict_items' object has no attribute 'keys'
错误是由以下原因引起的:
if username not in user_table.keys():
有什么错误的想法吗?
提前致谢!
【问题讨论】:
-
你为什么使用
.items()?users是一个字典。它有keys和get,您可以轻松地在其中查找内容。 -
这段代码是不是刚刚从这个 S/O 站点获得的?
-
user_table= users.items() user_names = user.keys() 这里 users 是一个字典, users.items() 将返回列表并获取键列表使用“user.keys() " 不是 "user_table.keys()"
-
在
with中,你应该使用if '-' not in line:,因为它更具可读性