如果x不在列表B中,如何使用:x代表列表a中的x将单词存储到文件中?

2024-10-05 17:44:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我将关键字存储到一个列表中:keywords=[a,b,c,d,e],其中a,b,c,d,e可以是任何单词 然后我尝试创建一个文件来存储单词。你知道吗

with open("KeyWordFile.txt", "a+",) as KeyWordFile:
    KeyWordFileItem = KeyWordFile.readlines()
    KeyWordFileItem = [word.strip() for word in KeyWordFileItem]
    KeyWordToBeStored = [x for x in keywords if x not in KeyWordFileItem]

    for x in KeyWordToBeStored: 
        KeyWordFile.write("%s\n" % x.encode("UTF-8"))

第一次运行代码时,成功地将单词存储到文件中。 但是,当我再次运行它时,它无法实现我想要的。我只想存储文件中还没有的单词。 结果:

a

b

c

d

e

a

b

c

d

e

我想要的是:

a

b

c

d

我不希望文件中出现任何重复的单词。你知道吗


Tags: 文件intxt列表foraswith关键字
3条回答

您可以使用set()分两步完成

with open("KeyWordFile.txt", "rt") as myfile:
    keywords = set([kw.strip() for kw in myfile])

with open("KeyWordFile.txt", "wt") as myfile:
    for kw in sorted(keywords):
        myfile.write("%s\n" % kw.encode("UTF-8"))

我认为您需要对关键字进行排序,否则可以删除sorted()函数。你知道吗

当打开带有标志a+的文件时,文件光标将自动定位在文件的末尾,因此您不能从文件中读取任何内容。解决这个问题的一种方法是使用seek(0) 方法回放光标

with open("KeyWordFile.txt", "a+",) as KeyWordFile:
    KeyWordFile.seek(0)
    KeyWordFileItem = KeyWordFile.readlines()
    KeyWordFileItem = [word.strip() for word in KeyWordFileItem]
    KeyWordToBeStored = [x for x in keywords if x not in KeyWordFileItem]

    for x in KeyWordToBeStored: 
        KeyWordFile.write("%s\n" % x.encode("UTF-8")) 

但是在read之前调用write时要小心,因为write会将光标移动到EOF,也许您可以尝试将这两部分分开

如果在测试中使用unicode字符,请尝试在此处添加decode

#KeyWordFileItem = [word.strip() for word in KeyWordFileItem]
KeyWordFileItem = [word.decode('utf-8').strip() for word in KeyWordFileItem]

相关问题 更多 >