Adding brackets to a list and sort it

Discussion in 'Python' started by Guilherme Romero, Jan 17, 2023.

  1. Guilherme Romero

    Guilherme Romero New Member

    Joined:
    Nov 19, 2021
    Messages:
    11
    Likes Received:
    0
    Trophy Points:
    1
    Gender:
    Male
    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.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice