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

标签 python python-3.x

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

相关文章:

c++ - 如何使用 Boost.Python 定义 Python 元类?

python-3.x - 如何在单词 'the' 之后找到最常用的名词?

python - python 的锁问题

javascript - 如何在selenium中控制滚动到底部的速度

python - 从 matplotlib 感知均匀尺度中检索颜色

python-3.x - Django 将 isbn10 传递给 url

python - 如何让脚本等待按下按钮?

c++ - 使用共享内存在 C++ 和 Python 之间进行快速通信

python - 对两个值的元组列表进行分组,并返回所有第三个值的列表

python - 在 Python 脚本中打印数字总和