2014-02-13 37 views
0

我目前有以下代碼:輸入一個字符串後,計算機將隨機抽取字母並嘗試將其與字符串中的字母進行匹配。這會重複,並且每次迭代計算機都會更接近猜測您的字符串。我想輸出輸入的初始字符串或「目標」以及爲獲得正確匹配所花費的迭代次數的字符串格式。我想輸出這個文本文件。到目前爲止,腳本生成一個文本文檔,但不輸出到它。我希望它在主循環的每次迭代之後保存數據。我有工作計劃,我只需要輸出的幫助,關於如何完成的任何想法?將循環數據輸出到python中的文本文檔中

這裏是我所取得的進展:解決這兩個原來的問題和一個在評論

import string 
import random 

possibleCharacters = string.ascii_lowercase + string.digits + string.ascii_uppercase + ' .,!?;:£$^%&*|' 

file = open('out.txt', 'w') 

again = 'Y' 
while again == 'Y' or again == 'y': 
    target = input("Enter your target text: ") 
    attemptThis = ''.join(random.choice(possibleCharacters) for i in range(len(target))) 
    attemptNext = '' 

    completed = False 
    generation = 0 
    while completed == False: 
     print(attemptThis) 
     attemptNext = '' 
     completed = True 
     for i in range(len(target)): 
      if attemptThis[i] != target[i]: 
       completed = False 
       attemptNext += random.choice(possibleCharacters) 
      else: 
       attemptNext += target[i] 
     generation += 1 
     attemptThis = attemptNext 

    genstr = str(generation) 
    print("Target matched! That took " + genstr + " generation(s)") 

    file.write(target) 
    file.write(genstr) 

    again = input("please enter Y to try again: ") 

file.close() 
+0

你的錯誤是不在文件寫作。你沒有顯示你的整個代碼,很難說它還有什麼錯誤。它應該寫入文件很好,除非你的循環在此之前終止。 – sashkello

+0

您的寫作代碼看起來很好。請注意,它可能不會實際寫入文件,直到調用file.close()爲止,例如。當再次!='Y',它退出循環。要在匹配目標後強制寫入文件,請在調用file.write之後調用''file.flush()''。 – Moritz

+0

@sashkello這是整個代碼,它沒有在IDE中出現錯誤,但它創建的文件,但不寫入它 – Downdog555

回答

1

  • 如何編寫循環的每次迭代後的文件:呼叫file.flush()file.write(...)

    file.write(target) 
    file.write(genstr) 
    file.flush() # flushes the output buffer to the file 
    
  • 對每一個「目標」和「genstring」之後添加一個換行符你寫的,好了,一個換行符添加到字符串(或任何你想要的其他輸出格式):)

    file.write(target + '\n') 
    file.write(genstr + '\n') 
    
+0

此外,如果您希望繼續重新打開程序並繼續寫入文件,我建議您使用'a'而不是'w' file = open(...,'w')。這樣它將字符串追加到最後,而不是擦除它並寫上它。 – AER

相關問題