Skip to content

Instantly share code, notes, and snippets.

@tombrad
Last active March 14, 2024 15:50
Show Gist options
  • Save tombrad/4697060 to your computer and use it in GitHub Desktop.
Save tombrad/4697060 to your computer and use it in GitHub Desktop.
8.4 Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split() function. The program should build a list of words. For each word on each line check to see if the word is already in the list and if not append it to the list. When the program completes, sort and print the resulting words …
fname = raw_input("Enter file name: ")
fh = open(fname)
lst = list() # list for the desired output
for line in fh: # to read every line of file romeo.txt
word= line.rstrip().split() # to eliminate the unwanted blanks and turn the line into a list of words
for element in word: # check every element in word
if element in lst: # if element is repeated
continue # do nothing
else : # else if element is not in the list
lst.append(element) # append
lst.sort() # sort the list (de-indent indicates that you sort when the loop ends)
print lst # print the list
@Inspire2023
Copy link

fname = input("Enter file name: ")

try :
fh = open(fname)
except:
print("File Does not Exist!")

lst = list()

for line in fh:
words = line.split()
for word in words:
if word in lst: continue

    lst.append(word)
lst.sort()

print(lst)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment