简体   繁体   English

如何读取行中的特定单词?

[英]How to read specific words in lines?

I'm new to this and currently I'm trying to create a sign up and log in system for my assignment and I did this. 我是新手,目前我正在尝试为我的任务创建一个注册和登录系统,我这样做了。

def signUp(): #USER SIGN UP
    name=(str(input("Name: ")))
    intake=(str(input("Intake: ")))
    hp=(str(input("Phone Number: ")))
    email=(str(input("E-mail: ")))
    tp=(str(input("Student ID: ")))
    pw=(str(input("Password: ")))
    OccupantsData=[name,intake,hp,email,tp,pw]
    file=open("Database.txt","a")
    file.write(str(OccupantsData)+"\n")
    file.close()

When I run this code, it'll save all the inputs into 'Database.txt' like this 当我运行这段代码时,它会将所有输入保存到'Database.txt'中

    ['James', 'Jul17', '1234', 'etc@etc.com', 'TP1234', 'password']

    ['Jon', 'Sep17', '5567', 'etc1@etc.com', 'TP2345', 'passwords']

    ['Han', 'Oct17', '7554', 'etc2@etc.com', 'TP5546', 'passwords1']

    ['Klye', 'Oct17', '2234', 'etc3@etc.com', 'TP0094', 'passwords2']

Now, i'm not sure how code the login... It should take in the TPnumber and make sure it matches the password on the line... When I code it this way, it only works for the TPnumber and password on the first line and it will not work for others... 现在,我不确定登录代码如何...它应该接受TPnumber并确保它与行上的密码匹配...当我以这种方式编码时,它只适用于TPnumber和密码第一行,它不适用于其他人......

def logIn(): #USER SIGN IN
    TP=str(input("Please input TP Number:"))
    password=input("Please input password:")
    f=open("Database.txt","r")
    user=f.read()
    if (TP) in user:
        if password in user:
            print("Welcome")
        else:
            print ("Username or Password doesn't match")
            logIn()
    else:
        print("Error")
        logIn()

What can I do to make it read the input username and password and not just the first line? 我该怎么做才能让它读取输入的用户名和密码,而不仅仅是第一行?

I'd recommend outputting a json file instead of a text file and look up data as a dictionary. 我建议输出一个json文件而不是文本文件,并将数据作为字典查找。 However, since you write lines that look like lists, you can evaluate the string as if it were an actual list with ast.literal_eval() . 但是,由于您编写的行看起来像列表,因此可以将字符串计算为具有ast.literal_eval()的实际列表。

Given 特定

A file Database.txt 一个文件Database.txt

['James', 'Jul17', '1234', 'etc@etc.com', 'TP1234', 'password']
['Jon', 'Sep17', '5567', 'etc1@etc.com', 'TP2345', 'passwords']
['Han', 'Oct17', '7554', 'etc2@etc.com', 'TP5546', 'passwords1']
['Klye', 'Oct17', '2234', 'etc3@etc.com', 'TP0094', 'passwords2']

created from this refactored function: 从这个重构函数创建:

def signup():
    """User sign up."""
    name  = str(input("Name: "))
    intake = (str(input("Intake: ")))
    hp = str(input("Phone Number: "))
    email = str(input("E-mail: "))
    tp = str(input("Student ID: "))
    pw = str(input("Password: "))
    occupants_data = [name, intake, hp, email, tp, pw]

    # Safely open/close files
    with open("Database.txt", "a") as f:
        f.write(str(occupants_data) + "\n")

Code

from ast import literal_eval


def login(): 
    """User sign in."""
    tp = str(input("Please input TP Number: "))
    password = str(input("Please input password: "))

    with open("Database.txt", "r") as f:
        for line in f.readlines():
            if not line or line =="\n":
                continue

            user_data = literal_eval(line)         # convert string-list to a list
            if tp == user_data[-2]:
                if password == user_data[-1]:
                    print("Welcome")
                    return
                else:
                    print ("Username or Password doesn't match")
                    return
        print("Error")

Demo 演示

在此输入图像描述


Details 细节

The signup() function was refactored by: signup()函数由以下重构:

  • lowercase function name according to PEP8 根据PEP8的小写函数名称
  • extra parentheses removed 删除了额外的括号
  • the with statement was used to safely open and close files with语句用于安全地打开和关闭文件

This can be used to generate the Database.txt file. 这可以用于生成Database.txt文件。

The login() function was refactored by: login()函数由以下重构:

  • lowercase function and variable names 小写函数和变量名
  • converting the password input to a string 将密码输入转换为字符串
  • using a with statement to handle the file 使用with语句来处理文件
  • iterating each line of the file, ignoring blank lines and newlines 迭代文件的每一行,忽略空行和换行符
  • list-like lines are converted to lists 类似列表的行将转换为列表
  • rather than search lists, data is more quickly pulled from fixed indices 而不是搜索列表,数据更快地从固定索引中提取
  • the loop short-circuits if an input is successful, otherwise an error is printed 如果输入成功,则循环短路,否则打印错误

The next concept you might consider is exception handling raising errors instead of printing them and handling user KeyboardInterupt to quit a prompt. 您可能考虑的下一个概念是异常处理引发错误而不是打印它们并处理用户KeyboardInterupt以退出提示。

In order to match the input with one or more of the txt file content, you need to loop over it. 为了使输入与一个或多个txt文件内容相匹配,您需要循环它。 Moreover, to check if password is in the list you have to cast it into string . 此外,要检查密码是否在列表中,您必须将其转换为字符串 So your login code would become: 所以你的登录代码将成为:

def logIn():  # USER SIGN IN
TP = str(input("Please input TP Number:"))
password = str(input("Please input password:"))
f = open("Database.txt", "r")
for line in f.readlines():
    if (TP) in line:
        if password in line:
            print("Welcome")
        else:
            print ("Username or Password doesn't match")
            logIn()
    else:
        print("Error")

Good Luck! 祝好运!

input() returns a string, so no need for explicit conversion with str() . input()返回一个字符串,因此不需要使用str()进行显式转换。 Better use with statement when dealing with file objects as it closes them automatically. 在处理文件对象时更好地使用with statement ,因为它会自动关闭它们。

Defining signUp() : 定义signUp()

def signUp(): #USER SIGN UP    
    name = input("Name: ")
    intake = input("Intake: ")
    hp = input("Phone Number: ")
    email = input("E-mail: ")
    tp = input("Student ID: ")
    pw = input("Password: ")

    OccupantsData = [name, intake, hp, email, tp, pw]

    with open("Database.txt", "a") as db:
        db.write(' '.join(OccupantsData)) # Writing it as a string

Calling signUp() : 调用signUp()

signUp()

Name: x
Intake: something
Phone Number: 123-456-7890
E-mail: x@email.com
Student ID: x123
Password: password
>>> 

Defining logIn() : 定义logIn()

def logIn(): #USER SIGN IN
    TP = input("Please input TP Number: ")
    password = input("Please input password: ")

    with open("Database.txt") as db:
        for line in db:
            line = line.split(' ') # Making it a list

            if TP in line:
                if password in line:
                    print("Welcome")
                else:
                    print ("Username or Password doesn't match")
                    logIn()
            else:
                print("Error")
                logIn()

Calling logIn() : 调用logIn()

logIn()

Please input TP Number: x123
Please input password: pass
Username or Password doesn't match
Please input TP Number: x123
Please input password: password
Welcome
>>> 

Python Tutorial says: Python教程说:

It is good practice to use the with keyword when dealing with file objects. 在处理文件对象时,最好使用with关键字。 The advantage is that the file is properly closed after its suite finishes, even if an exception is raised at some point. 优点是文件在套件完成后正确关闭,即使在某个时刻引发了异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM