2016-11-23 151 views
0

我如何得到這個程序將文件壓縮成單詞列表和位置列表來重新創建原始文件。然後取出壓縮文件並重新創建原始文件的全文,包括標點符號和大寫字母。我該如何解決這個問題?

startsentence = input("Please enter a sentence: ") 
sentence = (startsentence) 
a = startsentence.split(" ") 
dict = dict() 
number = 1 
positions = [] 
for j in a: 
    if j not in dict: 
     dict[j] = str(number) 
     number = number + 1 
    positions.append(dict[j]) 
print (positions) 


print(positions) 
f = open("postions.txt", "w") 
f.write(str(positions) + "\n" ) 
f.close() 

print(sentence) 
f = open("words.txt", "w") 
f.write(str(startsentence) + "\n" ) 
f.close() 
+0

你有問題嗎? – DeepSpace

+0

對不起,我說錯了,一秒鐘。 –

+0

不要使用'dict'作爲你隱藏標準python'dict'類型的變量名。 – AChampion

回答

0

目前你正在編寫出了整個startsentence而不僅僅是唯一的話:

f = open("words.txt", "w") 
f.write(str(startsentence) + "\n" ) 
f.close() 

你需要編寫只有唯一碼字和它們的索引,你已經創建了一個字典,那些單詞和他們的索引dict(順便說一句,你真的不應該使用dict作爲變量名,所以我會用dct)。你只需要(使用with語句)給他們寫出來的排序基於其數值:

with open("words.txt", "w") as f: 
    f.write(' '.join(sorted(dct, key=dct.get)) + '\n') 

假設你有位置的列表(BTW:這是很容易從0開始比1)和一個列表的話恢復很簡單:

with open('positions.txt') as pf, open('words.txt' as wf: 
    positions = [int(p) for p in pf.read().split()] 
    words = wf.read().strip().split() 

recovered = ' '.join(words[p] for p in positions) # p-1 if you start from 1 
+0

謝謝你,這幫助了很多。 –

相關問題