Adding brackets to a list and sorting 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:

. . . . . . .
1 fname = input("Enter file name: ")
2 fh = open(fname)
3 lst = list(fh)
4 new_lst = lst.split()
5 sorted_lst = new_lst.sort()
6 print(sorted_lst)

But I’m getting the error: ‘list’ object has no attribute ‘split’ on line 4

. . . . . . .

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.

Your problems are with step 3 and 4. You can’t just magically add a file to a list.

The pseudo code will be

  1. create an empty list for unique words (ex lstUniqueWords)
  2. Read the file (using readlines()) into a variable (ex lstFileLines). This new variable will be a string list
  3. For each line in the string list (use for var in lstFileLines: type statement)
    5a. split the line using var.split() into an list of words (ex lstFileWords)
    5b. loop through lstFireWords using same type of for loop as above. Check if new word is in lstUniqueWords (use if my_item not in some_list: check). If not in list, add word to list
  4. Sort the lstUniqueWords list using the sort() functionality as instructed
    7. Print the sorted list.

Thank you!

1 Like