gpt4 book ai didi

python - 如何将输入压缩到 txt 文件中?

转载 作者:行者123 更新时间:2023-11-30 23:02:02 24 4
gpt4 key购买 nike

我一直在努力寻找一种将用户输入压缩到 .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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com