我一直在努力寻找一种方法将用户的输入压缩为.txt文件。我需要将用户输入压缩到txt文件中,并且能够使用它的原始格式和大小写重新打开它。 我目前的代码是:
sentence = "ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT CAN YOU DO FOR YOUR COUNTRY"
listSentence = sentence.split(" ")
d = {}
i = 0
values = []
for i, word in enumerate(sentence.split(" ")):
if not word in d:
d[word] = (i+1)
values += [d[word]]
print(values)
file = open("listofwords.txt","w")
file.write(str(values))
file.close()
此代码只是为句子中的单词指定值,并替换重复的单词并将句子写入文件。
答案 0 :(得分:2)
结帐zlib:
sentence = "ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT CAN YOU DO FOR YOUR COUNTRY"
com = zlib.compress(sentence)
with open("listofwords.txt", "wb") as myfile:
myfile.write(com)
或者用于解压缩:
with open("listofwords.txt", "rb") as myfile:
com = myfile.read()
sentence = zlib.decompress(com)
答案 1 :(得分:1)
感谢所有的帮助,感谢Arman的回答。我也做了更多的环顾四周,我发现gzip也是一个很好的方法来做到这一点。我已经更改了程序,因此它可以有两个输入。
(?: ?\|.*?\|\ ?\;?)