2014-05-21 87 views
2
print (
""" Welcome to the code breaker game! 
     In this game you will have to change symbols into letters in order to decipher secret words. 
     0 - instructions 
     1 - start 
     2 - clues 
     3 - check your answers 
     4 - quit 
""") 

choice = input(" choice : ") 

if choice == ("0"): 
    text_file = open ("instructions.txt","r") 
    print (text_file.read()) 
    text_file.close() 

elif choice =="1": 
    text_file = open ("words.txt","r") 
    contents = text_file 
    print (text_file.read()) 
    text_file.close() 
    a = input("Please enter a symbol ") 
    b = input("Please enter a letter ") 

    newcontents = contents.replace(a,b) 
    contents = newcontents 
    print(contents,"\n") 
    text_file.close 


elif choice == "2": 
text_file = open ("clues.txt","r") 
print (text_file.read()) 
text_file.close() 

elif choice == "3": 
text_file = open ("solved.txt","r") 
print (text_file.read()) 
text_file.close() 

elif choice == "4": 
quit 

所以基本上我正在做一個計算機科學項目,我的任務是通過將符號替換爲字母來製作解碼遊戲,但是當我嘗試將代碼的一部分實際更改爲符號時出現此錯誤字母。什麼是「AttributeError:'_io.TextIOWrapper'對象在python中沒有屬性'replace'」?

也有什麼辦法讓這個循環(不使用while循環,因爲它們很複雜)?我基本上希望代碼在運行該程序時向我顯示A和B,並在選擇任何選項以選擇不同選項後爲我顯示。 (例如,我按0指示,然後可以選擇不同的選項,例如開始遊戲)。

+0

你實際上需要做的是從文件中取文本,做你想做的事,然後重寫那些數據。 –

+0

錯誤是:Traceback(最近調用最後一次): 文件「\\ server2.school.local \ pupils $ \ 11.jakub \ year 10 \計算機科學\計算機科學項目\ 10年計算機科學項目\代碼2014 \ NEWPYTHONCODE.py「,第26行,在 newcontents = contents.replace(a,b) AttributeError:'_io.TextIOWrapper'對象沒有屬性'replace' – user3661051

+0

我不能像項目說明所說我必須使用提供的.txts文件的 – user3661051

回答

2

你的這部分代碼:

text_file = open ("words.txt","r") 
contents = text_file 
print (text_file.read()) 
text_file.close() 

是沒有意義的。您正在將文件對象(而不是文件的內容)分配到contents。你然後print的內容,但不要把它們分配給任何東西。我想你想要的是:

with open("words.txt") as text_file: 
    contents = text_file.read() 
print(contents) 
+0

好吧,這幫助了很多,因爲它會隨着更改而打印編碼詞,但它不會要求我將一個符號與字母替代符號進行新的配對,你知道我該怎麼做嗎? – user3661051

+0

@ user3661051看到我對這個問題的評論。 SO上有很多重複的內容。 – jonrsharpe

相關問題