2017-05-04 77 views
-2

我已經完成了研究並且一直無法找到解決我的問題的方法。基本上我希望我的代碼能夠完成與現在一樣的工作,但我希望能夠用文本文件替換我的句子變量。這裏是我當前的代碼:試圖使用文本文件而不是字符串變量

from collections import OrderedDict 
sentence= ("I met a traveller from an antique land, Who said Two vast and     trunkless legs of stone. Stand in the desert. . . . Near them, on the sand, Half sunk a shattered visage lies, whose frown, And wrinkled lip, and sneer of cold command, Tell that its sculptor well those passions read Which yet survive, stamped on these lifeless things, The hand that mocked them, and the heart that fed; And on the pedestal, these words appear: My name is Ozymandias, King of Kings; Look on my Works, ye Mighty, and despair! Nothing beside remains. Round the decay Of that colossal Wreck, boundless and bare The lone and level sands stretch far away.").lower() 
words = sentence.split(' ') 
lst = list(OrderedDict.fromkeys(words)) 
numberLst = [] 
for i in words: 
    numberLst.append(lst.index(i)+1) 

words_str = ':'.join(words) 
numberLst_str = ':'.join(str(e) for e in numberLst) 

file = open("words.txt","w") 
file.write(words_str) 
file.close() 

file=open("numberlst.txt","w") 
file.write(numberLst_str) 
file.close() 

joinlst = " ".join(lst[i-1] for i in numberLst) 

file=open("joinlst.txt","w") 
file.write(joinlst) 
file.close() 

choice = input ("do you want to uncompress or compress the text file (type compress or uncompress)") 
if choice == "compress": 
    print (numberLst) 
else: 
    if choice == "uncompress": 
     print (joinlst) 

print("your choice was",choice) 

回答

0

這將讀取文件的全部內容filename到變量sentence。請注意,sentence還將包含任何換行符(或其他奇怪的編碼垃圾),您可能需要用split(...)和/或trim(...)調用過濾掉。

sentence = "" 
with open(filename, 'r') as f: 
    sentence = f.read() 
+0

歡呼m8cheers m8cheers m8cheers m8cheers m8cheers m8cheers m8cheers m8cheers m8cheers m8cheers m8cheers m8cheers m8cheers m8cheers m8cheers m8cheers m8cheers m8cheers m8cheers m8cheers m8cheers m8cheers m8cheers m8cheers M8 – alibongo

+0

@alibongo很高興我能幫助!請投票發表帖子,並選擇它作爲答案,如果它的工作:) – Treebasher

0
with open("some_text_file.txt", "r") as text: 
    for line in text: 
     #do your thing 

將在頂部和使用的線路從你的代碼替換句子。

相關問題