一些string.split() 魔法可以解决这个问题。我添加了一些逻辑来处理包含- 字符的用户名或密码
password.py
from pprint import pprint
def process_two_lines(line1: str, line2: str) -> dict:
# determine which of the 2 variables is the password
# and which is the username
if 'password' in line1.split('-')[0]:
passwordline = line1
userline = line2
else:
passwordline = line2
userline = line1
# the join is in case the password or username contains a "-" character
password = '-'.join(passwordline.split('-')[1:]).strip('\n')
username = '-'.join(userline.split('-')[1:]).strip('\n')
service = userline.split('username')[0]
return {
'username': username,
'password': password,
'service': service
}
def get_login_info(filename: str) -> dict:
# read file
with open(filename) as infile:
filecontents = infile.readlines()
result = []
# go through lines by pair
for index, line1 in enumerate(filecontents[::2]):
result.append(process_two_lines(line1, filecontents[(index*2)+1]))
return result
logininfo = get_login_info('test1.txt')
pprint(logininfo)
print('----------\n\n')
for index, line in enumerate(logininfo):
print(f'{index:2}: {line["service"]}')
service = int(input('Please select the service for which you want the username/password:\n'))
print(f'Username:\n{logininfo[service]["username"]}\nPassword:\n{logininfo[service]["password"]}\n')
test1.txt
TESTACCOUNTusername-test-user
TESTACCOUNTpassword-0R/bL----d?>[G
GOOGLEusername-google
GOOGLEpassword-V*biw:Y<%6k`?JI)r}tC
STACKOVERFLOWusername-testing
STACKOVERFLOWpassword-5AmT-S)My;>3lh"
输出
[{'password': '0R/bL----d?>[G',
'service': 'TESTACCOUNT',
'username': 'test-user'},
{'password': 'V*biw:Y<%6k`?JI)r}tC',
'service': 'GOOGLE',
'username': 'google'},
{'password': '5AmT-S)My;>3lh"',
'service': 'STACKOVERFLOW',
'username': 'testing'}]
----------
0: TESTACCOUNT
1: GOOGLE
2: STACKOVERFLOW
Please select the service for which you want the username/password:
2
Username:
testing
Password:
5AmT-S)My;>3lh"
原答案
password.py
from pprint import pprint
def get_login_info(filename: str) -> dict:
with open(filename) as infile:
filecontents = infile.readlines()
for line in filecontents:
if 'password' in line.split('-')[0]: # split needed to not get false positive if username == password
password = line.split('-')[1].strip('\n') # gets the part after the - separator, removing the newline
service = line.split('password')[0] # gets the service part
elif 'username' in line.split('-')[0]: # split needed to not get false positive if password == username
username = line.split('-')[1].strip('\n')
result = {
'username': username,
'password': password,
'service': service
}
return result
pprint(get_login_info('test0.txt'))
pprint(get_login_info('test1.txt'))
输出:
{'password': 'generatedpassword',
'service': 'servicename',
'username': 'usernameinput'}
{'password': 'generated password',
'service': 'GOOGLE',
'username': 'myusername'}