Forums

Adding brackets to a list and sort it

Hello,

I have the following assignment:

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() method. 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 in python sort() order as shown in the desired output. You can download the sample data at http://www.py4e.com/code3/romeo.txt

The output must be the following:

[‘Arise’, ‘But’, ‘It’, ‘Juliet’, ‘Who’, ‘already’, ‘and’, ‘breaks’, ‘east’, ‘envious’, ‘fair’, ‘grief’, ‘is’, ‘kill’, ‘light’, ‘moon’, ‘pale’, ‘sick’, ‘soft’, ‘sun’, ‘the’, ‘through’, ‘what’, ‘window’, ‘with’, ‘yonder’]

The following is the code I wrote:

. . . . . . .

fname = input("Enter file name: ")

fh = open(fname)

lst = list(fh)

for line in lst:

liner = line.split()

new_lst = str(liner)[1:-1]

print(new_lst)

. . . . . . .

The output I’m getting is an unsorted list of words without brackets. I tried to use the sort() function but I get an error. I believe that sort() function only works when there are brackets, am I right? Could someone please help on putting the brackets on the beginning and the end of the set of words and sort them?

Thanks very much.

You're getting the "list without brakcets" because you're printing each element in the list one at a time (that's what the new_lst variable contains when you print it). I'm guessing that when you try to sort, you are sorting new_lst and, since that is a single string, you get an error. Check your course notes about how to add elements to a list and use that to create a list and append each new element to the list and then sort that.