我将关键字存储到一个列表中: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
我不希望文件中出现任何重复的单词。你知道吗
您可以使用set()分两步完成
我认为您需要对关键字进行排序,否则可以删除
sorted()
函数。你知道吗当打开带有标志
a+
的文件时,文件光标将自动定位在文件的末尾,因此您不能从文件中读取任何内容。解决这个问题的一种方法是使用seek(0)
方法回放光标但是在
read
之前调用write
时要小心,因为write
会将光标移动到EOF
,也许您可以尝试将这两部分分开如果在测试中使用unicode字符,请尝试在此处添加
decode
:相关问题 更多 >
编程相关推荐