【问题标题】:How do I print back specific data from a list using user input?如何使用用户输入从列表中打印回特定数据?
【发布时间】:2020-04-29 15:05:11
【问题描述】:

总之,我正在尝试创建一个密码管理器。想法是程序会询问用户输入。 如果用户写“new”,程序会要求在网站上输入用户名和密码,然后将这些数据以列表的形式存储在文本文件中。

现在主要问题:

我希望能够访问选定的数据并让程序将文本文件中的数据打印给我。 例如: 我在程序中输入网站“google”以及用户名:“potato”和密码:“potato”

之后,程序会询问我还想做什么。如果我写“访问 google”,我想通过编程将特定于 google 输入的网站、用户名和密码返回给我。

这是必要的,因为我将添加几个不同的输入。

我不知道该怎么做,也没有导师。我希望有人能给出一个我可以学习的解决方案。

您将在下面找到我提出的基本代码。

请记住,我是初学者。谢谢。


vault = open("Passvault.txt", "r+")
list = []
action = input("What do you want to do? ")


def tit():
    global title
    title = input("Add website: ")
    return title


def user():
    global username
    username = input("Create username: ")
    return username


def passw():
    global password
    password = input("Create password: ")
    return password

running = True
while running:
    creation = True
    tit()
    user()
    passw()
    if action == "new":
        tit()
        user()
        passw()
        #I added a class here hoping that i could create a class with an argument referencing the title
        #so that when i type access "title" in the next if statement it would print back the data
        #relevant to the selected title
        class new(str(title)):
            list.append(tit)
            list.append(user)
            list.append(passw)


        vault.close()

    if action == "access" + title:
        creation = False
        print(title)
        print("Username: " + username)
        print("Password: " + password)
        vault.close()

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    这里是代码。此代码将用户名、密码和网站名称存储在 txt 文件中,并打印用户名和密码 w.r.t 网站名称。

        import re # used to search patterns.
        file_name = 'Passvault.txt'
        while True:
            action = input("What do you want to do? ")
            if action == 'new':
                title = input("Add website: ")
                username = input("Create username:")
                password = input('Create password')
                #writing data into the file
                with open (file_name,'a') as f:
                    data = f.write(f'{title} {username} {password}\n')  
    
            if 'access' in action:#if input contains access word
                website = action.split()[1].strip() #storing website name which is written after access
                #reading the data 
                with open(file_name,'r') as f:
                    data = f.read()
                #searching for all username password related to website
                username_pass = re.findall(f'{website}\s+(.*?)\n',data,re.S)#example google sachin 1234
                print('Website: ',website)
                print('Username, Password',username_pass)
    

    【讨论】:

    • 您能解释一下您的代码吗?如果它有效是一回事,但我也想理解它。就像“as f”是做什么的?还是 re 模块?
    • 它也不能正常工作。它只打印最新的标题用户名和密码输入。如果你输入2个网站,用户名和密码,它不会打印出第一个,只会打印出第二个。
    • 我已经用 cmets 更新了代码。现在它将适用于多个网站。你可以在这里了解更多关于 re 模块的信息docs.python.org/3/library/re.html 还有关于文件处理(打开)docs.python.org/3/tutorial/inputoutput.html
    • website = action.split()[1].strip() 此行会将输入拆分为一个列表。例如,访问 google 将变为 ['acess','google'] 然后我存储了索引 1 上的网站名称 google 并删除了空格(如果有多余的空格)所以在网站变量中我将有 'google'
    • re.findall(f'{website}\s+(.*?)\n',data,re.S) 此行搜索从网站名称到 \n(新行) 的模式.所以它会得到用户名和密码。 (.*?) 捕获网站和新行之间的数据。当我们在多行字符串中搜索模式时使用 re.S。
    【解决方案2】:

    我会给你一个比代码更具概念性的答案,因为这是一种更长期的交易。

    您要做的是使用json filesdictionaries 来存储您的数据,以便您可以按键搜索(请参阅字典链接)。

    一旦你完成了,你会想要将所有的东西都包装在一个 while 循环中的 def 中,像这样获取用户输入:

    def get_input():
        permitted_actions = ['new', 'access', 'exit']
        while True:
            action = input("What do you want to do? Valid actions: new, access or type EXIT to end the program.").strip().lower()
            if action not in permitted_actions:
                print(f"{action} is not a valid action!")
            elif action == 'new':
                #call another function to do stuff here
            elif action == 'access':
                #call another function to do stuff here
            elif action == 'exit':
                print("Shutting down...")
                break
    

    我会强烈建议不要为密码管理器创建自己的实际保管库,直到你真正打算使用它时更有经验,否则向它提供假密码和诸如此类的东西并学习。

    现在,当您添加网站数据时,您将阅读您的字典(请参阅字典链接)并获取与所述网站关联的密钥(如果存在),然后更新用户提供的信息。

    当您访问网站的数据时,您只需转到字典(请参阅字典链接)并获取与该网站密钥相关的信息(如果存在)。

    请记住,您将从 json 文件加载该字典(请参阅 json 链接)。

    如果你要让这个程序成为有人会使用的实际程序,你会使用某种适当的数据库(python3 本身就支持 sqlite)并使用带有加密和主密码的数据库。

    我希望这会为您指明正确的方向。

    【讨论】:

    • 我强烈建议您不要使用纯文本文件,因为密码管理器可以轻松打开和读取其他文件。就像条约破坏者所说的那样,您应该使用数据库或类似工具来执行此操作。使用像 sqlite3 这样的数据库将允许您安全地保存密码,并且您可以创建一个表来存储信息并轻松访问它,而无需加载字典并进行转换
    【解决方案3】:

    您可以将值保存为字典,并使用列表作为用户名和密码,然后使用 literal_eval 将字符串 dict 转换为 dict 并访问用户名和密码,以及使用自己的用户名和密码存储其他网站。

    website = 'google'
    username,password = 'potato', 'potato'
    
    filename = "yourfilehere"
    
    with open(filename, w) as f:
        f.write(str({website: [username,password]}))
        #This will save your data as a string dictionary will the data above
    
    #then read the file, get the dictionary and convert it then use its values
    from ast import literal_eval
    with open(filename, 'r') as f:
        data = f.read()
    
    data = literal_eval(data)
    #Then search dictionary for website
    found = data.get(website)
    #Then if it was successful get the username and password
    username = found[0]
    password = found[1]
    

    只要您在正在阅读的文件中仅将字典创建为字符串,您就可以使用此方法保存尽可能多的网站,并保存分配的用户名和密码。

    您可以在代码中添加一个 input() 来检查用户想要哪个站点的用户名和密码,然后在您的字典中搜索它。

    search = input("Enter the website: ")
    try:
        found = data.get(search)
        #add code here to get username and password
    except:
        print("failed to find a website matching: %s" % search")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-20
      • 1970-01-01
      • 2020-12-09
      相关资源
      最近更新 更多