简体   繁体   English

如何在单独的文本文件中找到特定的单词? (蟒蛇)

[英]How to find specific words in a separate text file? (PYTHON)

Im doing a homework assignment and will need to locate a specific word in python. 我正在做作业,需要在python中找到一个特定的单词。 Any help would be much appreciated. 任何帮助将非常感激。 I am quite new to coding. 我是编码新手。 I would like help on how to answer this question. 我想对如何回答这个问题有所帮助。

I have seen multiple tutorial's but none have helped me so far. 我看过多个教程,但到目前为止都没有帮助。

y=()
answer=str(input("Do you want to create an account, y or n?"))
if answer=="y":
  file = open("database.txt", "r")
  username = input("Enter a username :")
  password = input("Now enter a password :")
  file = open("database.txt","a")
  file.write (username)
  file.write (",")
  file.write (password)
  file.write("\n")
  file.close()

else:
  username1=input("Enter your username:") 
  password1=input("Now enter your password:") 
  for line in open("database.txt","r").readlines():
    login_info = line.split()
  if username1 == login_info and password1 == login_info:
    print("Incorrect")
  else:
    print("Correct")

I expected the output to say correct when all the criteria is met but instead it outputs correct when i enter anything. 我希望输出满足所有条件时说正确,但是当我输入任何内容时输出就正确。

The indentation in the second part of your code is messed up, because the if- and else-statement should be inside of the for loop. 在代码的第二部分缩进被搞砸了,因为如果-和else语句应该是里面的for循环。 Also you split the loaded lines into a list ( login_info ) but incorrectly check that against the username and password variables. 另外,您将加载的行拆分为一个列表( login_info ),但根据用户名和密码变量错误地进行了检查。 And you use the default split() function which uses a whitespace as a separator, but you use a comma. 并且您使用默认的split()函数,该函数使用空格作为分隔符,但使用逗号。 I also put the else statement out of the for loop, because otherwise it will print every time the line is not the one where the user is stored. 我还将else语句放在for循环之外,因为否则它将在每行不是存储用户的行时打印。 Try this for the second part: 尝试第二部分:

else:
  username1=input("Enter your username:") 
  password1=input("Now enter your password:") 
  for line in open("database.txt","r").readlines():
    login_info = line.split(",")
    if username1 == login_info[0] and password1 == login_info[1].replace("\n", ""):
       print("Correct")
       break #Exit the for loop if the user is found
  else: #Only executed when break is not called
    print("incorrect")

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

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