2013-11-04 84 views
1

我對Python很陌生。我試圖從格式的文本文件中提取數據:如何刪除Python中輸出文件中的重複條目?

85729塊尋址指數近似的文字檢索

85730基於自動查詢擴展發散 等等

輸出文本文件是一個單詞的列表,但沒有重複的條目。輸入的文本文件可能有重複。輸出將是這樣的:

解決

指數

近似

等....

我的代碼,到目前爲止,我能獲取單詞列表,但包含重複項。在輸入文件到輸出文件之前,我嘗試檢查是否有重複項,但輸出結果沒有反映出來。有什麼建議麼?我的代碼:

infile = open("paper.txt", 'r') 
outfile = open("vocab.txt", 'r+a') 
lines = infile.readlines() 
for i in lines: 
    thisline = i.split() 
    for word in thisline: 
     digit = word.isdigit() 
     found = False 
     for line in outfile: 
      if word in line: 
       found = True 
       break 
     if (digit == False) and (found == False): 
        outfile.write(word); 
        outfile.write("\n"); 

我不明白如何在Python中關閉循環。在C++或Java中,花括號可以用來定義for循環的主體,但我不確定它是如何在Python中完成的。誰能幫忙?

回答

1

Python循環由於縮進而關閉;左邊的空白具有語義意義。這樣可以避免您瘋狂地輸入大括號或do/od或其他內容,並且可以消除一些錯誤,其中縮進無意中無法準確反映您的控制流。你的輸入看起來不夠大,無法證明你的輸出文件存在循環(如果它的確如此,我可能會使用gdbm表),所以你可以做類似的事情(非常簡短地測試過):

#!/usr/local/cpython-3.3/bin/python 

with open('/etc/crontab', 'r') as infile, open('output.txt', 'w') as outfile: 
    seen = set() 
    for line in infile: 
     for word in line.split(): 
      if word not in seen: 
       seen.add(word) 
       outfile.write('{}\n'.format(word)) 
+0

更多空白:http://stromberg.dnsalias.org/~strombrg/significant-whitespace.html – dstromberg

+0

謝謝!這工作。我現在理解空格python格式。 – user2951046