Search code examples
pythonlistsortingcomparetext-files

Compare and add word if not found in the list


This is the code i am trying:

file1 = open("romeo.txt")
list_orig=[]
list_distinct=[]

for line in file1:
 words=line.split()
  list_orig=list_orig+words
  for word in words:
    if word in list_distinct:continue
    list_distinct= list_distinct+word
print (list_distinct)

Could you please help me correct the code? Not getting desired results.

I am looking for help in comparing word from romeo.txt file and compare each word with the existing list of words. (If word exists in list then discard it, if word doesn't exist then add it.) Print the sorted list.


Solution

  • ''''

    with open("romeo.txt", mode='r') as f:
            data = f.readlines()
    list_distinct = []
    
    for line in data:
      words = line.split()
      for word in words:
        if word not in list_distinct:
          list_distinct.append(word)
    list_distinct.sort()
    print(list_distinct)
    

    ''''