[英]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.