Learners will be able to:
- Split some text into a list
- Add / append each word to a list
- Sort the single words into alphabetcial order
In the lesson you will learn how to make a list, read text from a file. This text will be stored into a list and then sorted alphabetically. The list is a most versatile datatype available in Python, data can be stored between square brackets. The good thing about a list is that items in a list do not have to be the same data type.
Part 1: Append a basic list:
Part 1: Append a basic list:
- Below is a simple list, run the program, what happens and why?
- Now add some text to the list using the code a_simple_list.append("hello")
- What happens?
- Can you add 10 words to the list?
Part 2: Reading Text from a file:
- The next part of the project is to code a simple program to open a text file and read all the contents, how very James Bond!
- Run the program below and when promoted enter the file name text
- Look at line 2, what does it do?
- Look at line 4 what does it do?
- Add you own text from the internet to text2, can you get the code to read that text file?
Part 3: Splitting the lines into words:
- Once the text has been read from the file it needs to be split into single words so it can be appended to the list and counted.
- Look at the for loop on line 7, complete the missing parts to print single words.
- Note the code .split() it splits each line into single words.
Part 4: Append the words to a list:
- On line 2 create a list called my_list
- On line 3 print the list, it should be empty
- What does line 15 do?
- What does line 16 do?
- On line 17 use the append code you learnt in Part 1 to add each word to the my_list
Part 5: Sort the list Alphabetically:
- Look at the program below, the last part is to sort the words into alphabetical order
- One line 19 use the code name of your list.sort()
- Add code to line 20 to print out your final sorted list
- Why do some words like and, arc, are, appear halfway through the list?
- Now it is your turn, change the words in the text file and make your own hack