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 taking one element out of the list and then printing it. That is why there are no brackets (because you're printing a string, not a list). If new_lst is what you are trying to sort, then that also explains your error - you're just trying to sort a string and not a list.