我一直在努力寻找一种将用户输入压缩到 .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()
此代码只是为句子中的单词赋值并替换重复的单词,然后将句子写入文件。
最佳答案
查看 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)
关于python - 如何将输入压缩到 txt 文件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34691339/