2017-04-27 30 views
2

我對代碼沒有經驗,並且有關於我的GCSE Computer Science受控評估的問題。我已經走得很遠了,這只是最後一個障礙阻止了我。 這個任務需要我使用一個以前製作的簡單文件壓縮系統,並且「開發一個程序來建立一個文本文件,用一些句子來壓縮一個文本文件,包括標點符號,程序應該能夠將一個文件壓縮成一個文件列表中的單詞和位置列表以重新創建原始文件,還應能夠獲取壓縮文件並重新創建原始文件的全文,包括標點符號和大寫字母。我需要爲我的GCSE計算機科學制作一個簡單的文件壓縮系統

到目前爲止,我已經能夠一切爲文本文件存儲與我的第一個程序:

sentence = input("Enter a sentence: ") 
sentence = sentence.split() 
uniquewords = [] 
for word in sentence: 
    if word not in uniquewords: 
     uniquewords.append(word) 

positions = [uniquewords.index(word) for word in sentence] 
recreated = " ".join([uniquewords[i] for i in positions]) 

print (uniquewords) 
print (recreated) 

positions=str(positions) 
uniquewords=str(uniquewords) 

positionlist= open("H:\Python\ControlledAssessment3\PositionList.txt","w") 
positionlist.write(positions) 
positionlist.close 

wordlist=open("H:\Python\ControlledAssessment3\WordList.txt","w",) 
wordlist.write(uniquewords) 
wordlist.close 

這讓一切都變成清單,並將其轉換成一個字符串,這樣就可以寫成文本文件。現在,節目2就是問題所在:

uniquewords=open("H:\Python\ControlledAssessment3\WordList.txt","r") 
uniquewords= uniquewords.read() 

positions=open("H:\Python\ControlledAssessment3\PositionList.txt","r") 
positions=positions.read() 

positions= [int(i) for i in positions] 

print(uniquewords) 
print (positions) 

recreated = " ".join([uniquewords[i] for i in positions]) 

FinalSentence= 
open("H:\Python\ControlledAssessment3\ReconstructedSentence.txt","w") 
FinalSentence.write(recreated) 
FinalSentence.write('\n') 
FinalSentence.close 

當我嘗試運行此代碼,出現此錯誤:

Traceback (most recent call last): 
File "H:\Python\Task 3 Test 1.py", line 7, in <module> 
positions= [int(i) for i in positions] 
File "H:\Python\Task 3 Test 1.py", line 7, in <listcomp> 
positions= [int(i) for i in positions] 
ValueError: invalid literal for int() with base 10: '[' 

那麼,你怎麼想我得到的第二個程序重新編譯文字放入句子中?謝謝,我很抱歉,如果這是一個冗長的帖子,我已經花了很長時間試圖讓這個工作。 我假設這是與已被轉換成包括括號,逗號和空格等字符串的列表有關的事情,所以有沒有辦法將兩個字符串恢復到它們的原始狀態,以便我可以重新創建該句子?謝謝。

回答

1

所以首先,將職位作爲文字字符串保存是一件很奇怪的事情;您應該保存每個元素(與唯一的字相同)。考慮到這一點,是這樣的:

program1.py:

sentence = input("Type sentence: ") 

# this is a test this is a test this is a hello goodbye yes 1 2 3 123 

sentence = sentence.split() 
uniquewords = [] 
for word in sentence: 
    if word not in uniquewords: 
     uniquewords.append(word) 

positions = [uniquewords.index(word) for word in sentence] 

with open("PositionList.txt","w") as f: 
    for i in positions: 
      f.write(str(i)+' ') 

with open("WordList.txt","w") as f: 
    for i in uniquewords: 
      f.write(str(i)+' ') 

program2.py:

with open("PositionList.txt","r") as f: 
    data = f.read().split(' ') 
positions = [int(i) for i in data if i!=''] 

with open("WordList.txt","r") as f: 
    uniquewords = f.read().split(' ') 

sentence = " ".join([uniquewords[i] for i in positions]) 
print(sentence) 

PositionList.txt

0 1 2 3 0 1 2 3 0 1 2 4 5 6 7 8 9 10 

WordList.txt

this is a test hello goodbye yes 1 2 3 123 
+0

謝謝,明天我會盡量利用這個。這使得更有意義。 :) – Curtis