[英]I cant figure out how to make it not say added view to list every time i type view into the command
[英]How do I figure this out?
我如何獲得該程序將文件壓縮為單詞列表和位置列表,以重新創建原始文件。 然后,獲取壓縮文件並重新創建原始文件的全文,包括標點和大寫。
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()
當前,您正在寫出整個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')
假設您有一個職位列表(順便說一句:從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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.