Sort Words In Sequence Order In Which They Were Saved
Solution 1:
lines_set = {line.strip() for line in lines}
This is creating a set object for you, and sets do not have any order. I'd use a list for this task to preserve the order they are added:
withopen('D:\path\file.txt', 'r') as lines:
lines_set = []
for line in lines:
if line.strip() notin lines_set: # Keep only unique words
lines_set.append(line.strip())
Lines need to be iterated through the long way like this so that only the unique words can be kept.
Solution 2:
First of all it is a good idea to update your question if it changed. Most people do not read all comments under the answers to find your problem.
Now to your question:
It is often a good idea to analyse the code line by line.
import random # In this code snippet it is not used?print ('Write word : ') # printing something
text = input ('') # get some input -> text
data = open ('D:\path\file.txt', 'a') #open new file (appending)
data.write (text) # write user input at file ending
data.write('\n') # write line break at file ending
Wait! You want only append a line if it not exists already...
So let us include a test for that
print ('Write word : ')
text = input('')
data = open ('file.txt', 'a') #Add new word to new linewithopen('file.txt', 'r') as lines:
if text.strip() notinmap(str.strip, lines): # Keep only unique words
data.write(text)
data.write('\n')
data.close()
That will check if the line already exists. Maybe the map function is a little bit confusing, but it only applies the function strip to all lines in the file to get rid of extra space and new line characters.
Now it should work :)
Post a Comment for "Sort Words In Sequence Order In Which They Were Saved"