繁体   English   中英

如何用#替换文本文件中的重复项?

[英]How to replace duplicates in a text file with a #?

对于我的班级项目,我必须创建一个简单的Username Inventor并将Usernames存储在文件中。 这是我所做的并且正在起作用。

该项目的另一部分是,如果将重复项添加到文件中,则该重复项需要删除并替换为“#”。 但是“#”必须位于重复的原始用户名旁边。

请有人告诉我如何执行此操作,作为参考,以下是我的代码:

print("Hello, Welcome to the Username Inventor.")
Name = input("Please tell me, What is your name? ")
print(Name+"......")
print("I like....")
print("Anyway, lets get on shall we.")
with open("Interim.txt", "a") as file:
    true = True
    while true == True:
        choice = input("(1)Add a Pupil's Username to the file\n(2)Exit the program\n")
        if choice == "1":
            true = False
            print("Please identify the following:")
            FirstName = input("Pupil's First Name: ")
            Surname = input("Pupil's Surname: ")
            YearOfEntry = input("Pupil's Year of Entry: ")
            print("Thank you",FirstName, Surname, "from year joining at",YearOfEntry+".")
            Initial = FirstName[0]
            Username = YearOfEntry+Surname+Initial
            print("This Pupil's Username is",Username+".")
            file.write(Username)
            file.write("\n")
            true = True
        if choice == "2":
            print("Thank you", Name+". Goodbye!")
            true = False

非常感谢您的帮助,谢谢。

您可以使用列表来检查列表中是否已经有新的用户名。 创建一个列表并将用户名添加到列表中。 在将用户名写入文件之前,使用'if'语句检查用户名是否已在列表中(如果已存在),然后检查file.write(“#\\ n”),否则检查file.write(“ username”)。

替换以下两行:

file.write(Username)
file.write("\n")

对于:

username_list = [] #make empty list before your with open statement.
    ...
    if Username not in username_list:
        file.write('%s\n'%Username)
        username_list.append(Username)

    else:
        file.write('#\n')
        username_list.append("#")

暂无
暂无

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

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