如何使 Python 程序在遍历列表后自动打印匹配的内容

How to make a Python program automatically prints what matched after iterating through lists

我有这个 Python 代码:

with open('save.data') as fp:
    save_data = dict([line.split(' = ') for line in fp.read().splitlines()])

with open('brute.txt') as fp:
    brute = fp.read().splitlines()

for username, password in save_data.items():
    if username in brute:
        break
else:
    print("didn't find the username")

这是一个简单的解释; save.data 是一个包含批处理文件游戏变量(例如用户名、hp 等...)的文件,brute.txt 是一个包含 "random" 字符串的文件(如在用于暴力破解的词表)。

save.data:

username1 = PlayerName
password1 = PlayerPass
hp = 100

正如我之前所说,这是一个批处理文件游戏,所以不需要引用字符串

brute.txt:

username
usrnm
username1
password
password1
health
hp

所以,我们假设 Python 文件是一个 "game hacker" "brute" 批处理文件的游戏保存文件,希望找到匹配项,当它找到时,它会检索并将它们显示给用户。

## We did all the previous code
...
>>> print(save_data["username1"])
PlayerName

成功!我们检索了变量!但我想让程序能够显示它自己的变量(因为我知道 "username1" 是匹配的,这就是我选择打印它的原因)。我的意思是,我想让程序 print 成为匹配的变量。例如:如果 save.data 中没有 "username1" 而有 "usrnm",它肯定会在 "bruting" 过程后被识别,因为它已经在 brute.txt 中。那么,如何让程序print匹配什么?因为我不知道它是 "username" 还是 "username1" 等...该程序确实 :p (当然没有打开 save.data)当然这并不意味着该程序会只搜索用户名,这是一个游戏,应该还有其他变量,如 gold/coins、hp 等...如果你不明白什么,请评论它,我会清理它,感谢你的时间!

使用像这样的dict

with open('brute.txt', 'r') as f:
    # First get all the brute file stuff
    lookup_dic = {word.strip(): None for word in f.readlines()}
with open('save.data', 'r') as f:
    # Update that dict with the stuff from the save.data
    lines = (line.strip().split(' = ') for line in f.readlines())
    for lookup, val in lines:
        if lookup in lookup_dic:
            print(f"{lookup} matched and its value is {val}")
            lookup_dic[lookup] = val
# Now you have a complete lookup table.
print(lookup_dic)
print(lookup_dic['hp'])

输出:

username1 matched and its value is PlayerName
password1 matched and its value is PlayerPass
hp matched and its value is 100
{'username': None, 'usrnm': None, 'username1': 'PlayerName', 'password': None, 'password1': 'PlayerPass','health': None, 'hp': '100'}
100