[英]Python: Issue with Writing over Lines?
因此,这是我在Python中用于删除行的代码,因此被称为“清理”。 我列出了几千个单词及其词性:
神经网络
PP在
PP在
...这就是问题。 出于某种原因(我无法弄清并尝试了几个小时),我用来检查输入单词的程序不会清除重复项,因此,我能做的下一件最好的事情是前任的! 是的,循环浏览文件并删除运行中的重复项。 但是,每当我这样做,这个代码,而不是采用列表的最后一行,并重复说的几十万次。
有什么想法吗? :(
编辑:这个想法是cleanseArchive()会通过一个名为words.txt的文件,将所有重复的行删除。 但是,由于Python无法删除行,而且我还没有其他方法的运气,因此我转向了本质上将非重复数据保存在列表(saveList)中,然后从该列表中写入每个对象放入新文件(删除旧文件)。 但是,就目前而言,它只是成千上万次重复了原始列表的最终对象。
EDIT2:这是我到目前为止的内容,并从答复中获取建议:
def cleanseArchive():
f = open("words.txt", "r+")
given_line = f.readlines()
f.seek(0)
saveList = set(given_line)
f.close()
os.remove("words.txt")
f = open("words.txt", "a")
f.write(saveList)
但是在ATM机上,我会遇到以下错误:
Traceback (most recent call last):
File "C:\Python33\Scripts\AI\prototypal_intelligence.py", line 154, in <module>
initialize()
File "C:\Python33\Scripts\AI\prototypal_intelligence.py", line 100, in initialize
cleanseArchive()
File "C:\Python33\Scripts\AI\prototypal_intelligence.py", line 29, in cleanseArchive
f.write(saveList)
TypeError: must be str, not set
for i in saveList:
f.write(n+"\n")
您基本上一遍又一遍地打印n
的值。
尝试这个:
for i in saveList:
f.write(i+"\n")
如果您只想删除“重复的行”,我已经修改了您的阅读代码:
saveList = []
duplicates = []
with open("words.txt", "r") as ins:
for line in ins:
if line not in duplicates:
duplicates.append(line)
saveList.append(line)
此外,请采取上述更正!
def cleanseArchive():
f = open("words.txt", "r+")
f.seek(0)
given_line = f.readlines()
saveList = set()
for x,y in enumerate(given_line):
t=(y)
saveList.add(t)
f.close()
os.remove("words.txt")
f = open("words.txt", "a")
for i in saveList: f.write(i)
完成的产品! 我最终研究了枚举,本质上只是使用它来获取字符串。 伙计,当您进入集合/列表时,Python会有一些坎bump的道路,这真是太糟糕了。 太多东西由于非常模棱两可的原因而无法正常工作! 无论如何,将其修复。
让我们整理一下您在更新中提供的代码:
def cleanseArchive():
f = open("words.txt", "r+")
given_line = f.readlines()
f.seek(0)
saveList = set(given_line)
f.close()
os.remove("words.txt")
f = open("words.txt", "a")
f.write(saveList)
我们有一些不好的名字,不尊重《 Python代码样式指南》 ,我们有多余的代码部分,我们没有充分利用Python的强大功能,并且部分代码无法正常工作。
让我们从删除不需要的代码开始,同时使用有意义的名称。
def cleanse_archive():
infile = open("words.txt", "r")
given_lines = infile.readlines()
words = set(given_lines)
infile.close()
outfile = open("words.txt", "w")
outfile.write(words)
不需要seek
,打开文件以读取的模式现在为r
,写入模式为w
,我们删除了删除文件的步骤,因为无论如何它都会被覆盖。 看一下我们现在看到的这段更清晰的代码,我们错过了写入后关闭文件的过程。 如果我们使用with
语句打开文件,Python将为我们处理。
def cleanse_archive():
with open("words.txt", "r") as infile:
words = set(infile.readlines())
with open("words.txt", "w") as outfile:
outfile.write(words)
既然我们有了清晰的代码,我们将处理在调用outfile.write
时发生的错误消息: TypeError: must be str, not set
。 此消息很清楚:您不能将集合直接写入文件。 显然,您必须遍历集合的内容。
def cleanse_archive():
with open("words.txt", "r") as infile:
words = set(infile.readlines())
with open("words.txt", "w") as outfile:
for word in words:
outfile.write(word)
而已。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.