Python-阅读和追加文件

时间:2015-05-09 12:57:07

标签: python file append

我正在尝试创建一个程序,要求用户输入“name”并检查以确保名称是字母,而不是太长,而不是在名为Unacceptable_Names(包含不适当的名称)的文件中

为了确保程序的每个用户不使用相同的名称,当玩家输入名称时,我将其附加到Unacceptable_Names,然后当下一个玩家玩它时,如果他们输入名称,则应该给他们一个错误这个文件。

下面的代码适用于已在文件中创建的单词,但是当我重放并输入相同的名称时,我不会收到错误。有人可以帮助解决为什么不检查名称的原因吗?

def Char_Name(self,name):
    string1=str(name).lower()
    unacceptable_names=open("C://Users//Documents//Unacceptable_Names.txt", "r")
    unacceptable_names2=open("C://Users//Documents//Unacceptable_Names.txt", "a")
    names_list= []
    for line in unacceptable_names.readlines():
        for i in line.split(","):
            names_list.append(i.strip())
    if name.isalpha()==False:
        print("You entered a name containing non-alphabetic characters, pease reenter a new name:")
        main()
    elif len(name)>=10:
        print("You entered a name containing 10 or more characters, pease reenter a new name:")
        main()
    elif string1 in names_list:
        print("You entered a name containing bad words or a name already in use! Try again.")
        main()
    else:
        unacceptable_names2.write("\n"+str(name)+",")
        unacceptable_names2.close()
        self.character_name=name

这是在输入名称“Emily”之后不可接受的名字的样子:[以及之前文件中的其他一些坏词 - 如果输入则会给我一个错误]

皱巴巴的海星, XX, XXX, YAOI, 黄色淋浴, yiffy, 动物恋, 艾米丽,

但是,如果我手动进入文本文件并写上“Emily”的确切内容,它会给我提供我需要的错误信息。

4 个答案:

答案 0 :(得分:1)

此行unacceptable_names2.write(name)将名称附加到同一行。 每个名称后面都应该有,的每个名称。只有这样

for line in unacceptable_names.readlines():
        for i in line.split(","):
            names_list.append(i.strip())`

的工作。

unacceptable_names2.write(name)之后的当前文件内容:

helloonetwothree

你想要的是什么:

hello,one,two,three

更新的代码:

def Char_Name(self,name):
    string1=str(name).lower()
    unacceptable_names=open("C://Users//Documents//Unacceptable_Names.txt", "r")
    unacceptable_names2=open("C://Users//Documents//Unacceptable_Names.txt", "a")
    names_list= []
    for line in unacceptable_names.readlines():
        for i in line.split(","):
            names_list.append(i.strip())
    if name.isalpha()==False:
        print("You entered a name containing non-alphabetic characters, pease reenter a new name:")
        main()
    elif len(name)>=10:
        print("You entered a name containing 10 or more characters, pease reenter a new name:")
        main()
    elif string1 in names_list:
        print("You entered a name containing bad words or a name already in use! Try again.")
        main()
    else:
        unacceptable_names2.write(name+',')
        unacceptable_names2.close()
        self.character_name=name

更新

i.strip()添加到上面的代码中。 您以某种方式在每个名称的开头添加一个空格。 因此,当您搜索yiffy时,无法找到匹配项。因为它存储为yiffy

In [54]: 'wrinkled starfish, xx, xxx, yaoi, yellow showers, yiffy, zoophilia, Emily,'.split(','
   ....: )
Out[54]: 
['wrinkled starfish',
 ' xx',
 ' xxx',
 ' yaoi',
 ' yellow showers',
 ' yiffy',
 ' zoophilia',
 ' Emily',
 '']

答案 1 :(得分:0)

def Char_Name(self,name):
    string1=str(name).lower()
    unacceptable_names=open("C://Users//Documents//Unacceptable_Names.txt", "r")
    unacceptable_names2=open("C://Users//Documents//Unacceptable_Names.txt", "a")
    names_list= []
    for line in unacceptable_names.readlines():
        for i in line.split(","):
            names_list.append(i)
    if name.isalpha()==False:
        print("You entered a name containing non-alphabetic characters, pease reenter a new name:")
        main()
    elif len(name)>=10:
        print("You entered a name containing 10 or more characters, pease reenter a new name:")
        main()
    elif string1 in names_list:
        print("You entered a name containing bad words or a name already in use! Try again.")
        main()
    else:
        unacceptable_names2.write(',' + str(name) ) # <------- 
        unacceptable_names2.close()
        self.character_name=name

或者您可以将上次else更改为:

else:
        unacceptable_names2.write('\n' + str(name) + '\n')
        unacceptable_names2.close()
        self.character_name=name

答案 2 :(得分:0)

您还应确保完全匹配名称。如果你只是在python中匹配,它可能会将一个名称混淆为另一个名称。例如,有两个用户名相似的用户示例: 1)梅根 2)Megan2015。 在一个简单的匹配案例中:如果你搜索Megan,python可能会找到Megan2015并说它找到了它,因为&#34; Megan&#34;在&#34; Megan2015&#34;

def exact_match(phrase, word):
import re

b = r'(\s|^|$)'
res = re.match(b + word + b, phrase, flags=re.IGNORECASE)
return bool(res)  # returns true or false

def Char_Name(self,name):

string1=str(name).lower()
unacceptable_names=open("C://Users//Documents//Unacceptable_Names.txt", "r")
unacceptable_names2=open("C://Users//Documents//Unacceptable_Names.txt","a")
names_list= []

for line in unacceptable_names.readlines():

    for i in line.split(","):
        names_list.append(i)

if name.isalpha()==False:
    print("You entered a name containing non-alphabetic characters, please  reenter a new name:")
    main()

elif len(name)>=10:
    print("You entered a name containing 10 or more characters, pease reenter a new name:")
    main()

elif:
    for n in range(0,len(names_list)):

        if exact_match(string1, names_list[n]) == True:
            print("You entered a name containing bad words or a name already in use! Try again.")
            main()
else:
    unacceptable_names2.write(str(name + " , ") )
    unacceptable_names2.close()
    self.character_name=name

答案 3 :(得分:0)

你应该在不同的行上写下每个名字,你根本不需要aplit,在打开文件时创建一组名称,并使用+打开一次进行阅读和追加:

def Char_Name(self,name):
    string1 = name.lower()
    with open("C://Users//Documents//Unacceptable_Names.txt", "a+") as f:
        unacceptable_names = set(line.rstrip() for line in f)
    if not name.isalpha():
        print("You entered a name containing non-alphabetic characters, please re-enter a new name:")
        main()
    elif len(name) >= 10:
        print("You entered a name containing 10 or more characters, please re-enter a new name:")
        main()
    elif string1 in unacceptable_names:
        print("You entered a name containing bad words or a name already in use! Try again.")
        main()
    f.write("{}\n".format(name))
    self.character_name = name

使用pickle存储一组名称可能更好。

我还会使用while循环询问用户在循环中的名字,而不是重复调用main。

def Char_Name(self):
    with open("C://Users//Documents//Unacceptable_Names.txt", "a+") as f:
        unacceptable_names = set(line.rstrip() for line in f)
    while True:
        name = input("Please enter your username")
        _name = name.lower()
        if _name in unacceptable_names:
            print("You entered a name containing bad words or a name already in use! Try again.")
        elif _name.isalpha():
            print("You entered a name containing non-alphabetic characters, please re-enter a new name:")
        elif len(name) >= 10:
            print("You entered a name containing 10 or more characters, please re-enter a new name:")
        else:
            break
    f.write("{}\n".format(name))
    self.character_name = name

除非你真的需要一个列表,否则不需要使用readlines,如果你要构建一个名称容器,那么set是检查成员资格的最有效方法。