Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

Python 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:

. . . . . . .
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.
 
Hey so the issue you have is your making a list with:
Python:
lst = list(fh)

then your trying to make a list again with a list with:
Python:
new_lst = lst.split())

what you will need to do is loop the list you just created then you can turn each of the first lists into a new list if that makes sense.
I have done the code for you so you can see how i would do it :D

Python:
#fname = input("Enter file name: ")
#fh = open(fname)

#First open text file
fh = open("romeo.txt")

complete = []
#loop each line and split
for line in list(fh):
    #split line into list
    for subline in line.split():
        #if not in the complete list then add if not ignore
        if subline not in complete:
            complete.append(subline)

print(complete)
 
The assignment says to read the file line by line. Which is silly because there is no need for that. Check this shorter solution (the required sort added for good measure) :

Python:
fh = open("romeo.txt")
wordlist = []
for word in fh.read().split():
    if word not in wordlist:
         wordlist.append(word)
wordlist.sort()
print(wordlist)
 
To add to simong1993's example instead of fh = open('romeo.txt'), the preferred method is to use with open(filename, 'r') as fh. That way you do not have to worry about closing the file.
Another example using list comprehension.

Python:
# Text file
file = 'romeo.txt'

# Create empty list
word_list = []

# Use with open as not have to worry about closing file
with open(file, 'r') as myfile:

    # Read the lines of the file
    lines = myfile.readlines()


[word_list.append(word) for line in lines for word in line.split() if word not in word_list]

word_list.sort()
print(word_list)

output

Code:
['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']
 
I think @cbreemer example would be great for us programmers who have been doing this a while lol, its short its sweet, we understand what it does and there is less code to read but mine is designed to be a bit longer but easier for someone new to follow and understand, broken down a bit so you can see each section one by one :)
 
I think @cbreemer example would be great for us programmers who have been doing this a while lol, its short its sweet, we understand what it does and there is less code to read but mine is designed to be a bit longer but easier for someone new to follow and understand, broken down a bit so you can see each section one by one :)
The only significant difference is that your version has two loops, and mine only one. Should not be any harder to understand even for a new programmer 😀
Yes I did leave out the comments 😁
 
@cbreemer version using list comp

Python:
# File to read
file = 'romeo.txt'

# Open file and read all lines. / Creates a list of lines
with open(file, 'r') as myfile:
    lines = myfile.read().split()

# Create an empty list
words = []

# Loop through and append word if not already in word list
[words.append(word) for word in lines if word not in words]

# Sort the list
words.sort()

# Print list
print(words)
 
Its this bit:-

Python:
[word_list.append(word) for line in lines for word in line.split() if word not in word_list]

for someone new to python it works and i understand what's happening lol but for someone new it could be troublesome lol
 
Is that a typical Python thing, putting a bunch of statements in reverse order between square brackets ? IMO it's just horrible, an abomination I have not seen in any other language as yet. I really think they have put too much effort in being different for the sake of being different. But well, ultimately it is a matter of taste.
 

New Threads

Latest posts

Buy us a coffee!

Back
Top Bottom