我该如何解决这个问题?
问题描述:
我如何得到这个程序将文件压缩成单词列表和位置列表来重新创建原始文件。然后取出压缩文件并重新创建原始文件的全文,包括标点符号和大写字母。我该如何解决这个问题?
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')
假设你有位置的列表(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
谢谢你,这帮助了很多。 –
你有问题吗? – DeepSpace
对不起,我说错了,一秒钟。 –
不要使用'dict'作为你隐藏标准python'dict'类型的变量名。 – AChampion