首页 > 解决方案 > 如何让 Python 程序在遍历列表后自动打印匹配的内容

问题描述

我有这个 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的文件,并且是一个包含“随机”字符串的文件(就像在用于暴力破解的单词列表中看到的那样)。

save.data

username1 = PlayerName
password1 = PlayerPass
hp = 100

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

brute.txt

username
usrnm
username1
password
password1
health
hp

因此,让我们假设 Python 文件是一个“游戏黑客”,它“暴力破解”批处理文件的游戏保存文件以希望找到匹配项,当它找到匹配项时,它会检索它们并将它们显示给用户。

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

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

标签: pythonpython-3.xlistloopsbrute-force

解决方案


使用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

推荐阅读