简体   繁体   中英

How do I compress an input into a txt file?

I have been struggling to find a way to compress an input from a user into a .txt file. I need to compress the users input down into the txt file, as well as being able to re-open it with it's original format and capitalization. The current code I have is:

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()

This code simply assigns values to the words in the sentence and replaces repeated words and writes the sentence to the file.

Check Out 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)

Or for decompress:

with open("listofwords.txt", "rb") as myfile:
    com = myfile.read()
sentence = zlib.decompress(com)

Thanks for all of the help, and to Arman for his answer. I also did more looking around and I have found out gzip also is a good way to do this. I have changed the program so it can have two inputs.

sentences = input("Enter the text you want to compress: ")
name = input("Please enter your desired file name: ")
with gzip.open(filename + ".gz", "wt") as outfile:
     outfile.write(plaintext)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM