Reputation: 57
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.
Upvotes: 1
Views: 1690
Reputation: 57
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)
Upvotes: 1
Reputation: 4528
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)
Upvotes: 2