[英]How to pull specific parts of a list on each line?
我有一個列表,它會吐出這樣的信息: ['username', 'password'], ['username', 'password'], ['username', 'password']
等等..
我希望以后能夠提取特定的用戶名和密碼。 例如: ['abc', '9876'], ['xyz', '1234']
拉abc
並告訴他們密碼是9876
。 然后拉xyz
告訴他們密碼是1234
我試着弄亂列表,我只是在如何做到這一點上畫了一個空白。
lines = []
with open("output.txt", "r") as f:
for line in f.readlines():
if 'Success' in line:
#get rid of everything after word success so only username and password is printed out
lines.append(line[:line.find("Success")-1])
for element in lines:
#split username and password up at : so they are separate entities
#original output was username:password, want it to be username, password
parts = element.strip().split(":")
print(parts)
我想提取每個用戶名,然后如上所述提取他們的密碼
通過此運行后的當前輸出是['username', 'password']
。 原始輸出文件有我刪除的額外信息,這些信息是涉及“成功”的代碼處理的
我想在沒有硬編碼用戶名的情況下做到這一點。 我正在嘗試自動執行此過程,以便它遍歷每個用戶名並將其格式化為"hi [username}, your password is [123]"
,對於所有用戶名
后來我希望能夠只告訴特定用戶他們的密碼。 例如,我想向用戶 abc 發送一封電子郵件。 該電子郵件應僅包含用戶 abc 的用戶名和密碼
不要打印parts
,而是將它們附加到列表中。
data = []
for element in lines:
parts = element.strip().split(":")
data.append(parts)
然后你可以將這些轉換成字典進行查找
username_passwords = dict(data)
print(username_passwords['abc'])
如果我理解正確,部分是包含 [用戶名:密碼] 的列表。 如果是這種情況,我們可以將應該只有 2 個元素的部分的每個值分配給字典作為字典對,然后稍后調用用戶名。
lines = []
User_Pass = {}
with open("output.txt", "r") as f:
for line in f.readlines():
if 'Success' in line:
#get rid of everything after word success so only username and password is printed out
lines.append(line[:line.find("Success")-1])
for element in lines:
#split username and password up at : so they are separate entities
parts = element.strip().split(":")
User_Pass.update({parts[0] : parts[1]})
然后,如果您知道用戶名,則可以從用戶名中調用密碼,如下所示:
x = User_Pass["foo"]
或者如您在評論中所述:
for key, value in User_Pass.items():
print('Username ' + key + ' Has a Password of ' + value)
看起來像你這樣做之后
lines.append(line[:line.find("Success")-1])
行 = ['用戶名:密碼','用戶名:密碼'...]
所以我會這樣做
new_list_of_lists = [element.strip().split(":") for element in lines]
new_list_of_lists 現在應該看起來像 [[username, password], [username, password]]
然后就這樣做:
dict_of_usernames_and_passwords = dict(new_list_of_lists)
使用字典,您現在可以使用用戶名檢索密碼。 喜歡:
dict_of_usernames_and_passwords['abc']
您可以使用 json 模塊將 dict 保存到文件中,以便於檢索。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.