May-01-2019, 09:29 PM
How do I count how many words there are in the last line of a file?
Here are the contents of the text file:
Here is the script I wrote including annotations explaining my understanding what what is going on, line by line:
There are three variables in operation at line 9:
Why is the number of characters from the last line not printing?
For my personal future reference, I’m working on Jose Portilla’s public GitHub repo for his open course on Udemy at this specific module: Python-Narrative-Journey/02-Field-Readiness-Exam-1/01-Field-Readiness-Exam-One.ipynb
Here are the contents of the text file:
Quote:Welcome to your First Exam Recruit.
Only the best recruits can become agents.
Do you have what it takes?
We will test your knowledge with this field readiness exam.
It should be pretty simple, since you only know the basics so far.
Let's get started.
Best of luck recruit.
Here is the script I wrote including annotations explaining my understanding what what is going on, line by line:
with open('field.txt') as field_variable: # Opening the file as a variable field_variable = field_variable.readlines() # Reading the file list(field_variable) # Turning file contents into a list for i in field_variable: # Splitting each line in the list i.split() last = field_variable[-1] # Assigning the last line from the bottom by reverse slicing to a variable called, last for n in last: # Loop through last line num_chars = last.split(n) # Split last variable, assign to new variable, num_chars result = last.count(num_chars) # Now count number of list items print(result) # Print final_charsAccording to my interpreter, the problem is at line 9:
python--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-27-082decdb195e> in <module> 7 for n in last: # Loop through last line: 8 num_chars = last.split(n) # Split last variable, assign to new variable, num_chars ----> 9 final_chars = last.count(num_chars) # Now count number of list items 10 print(final_chars) # Print final_chars TypeError: must be str, not listApparently Python is expecting “a string, not a list”.
There are three variables in operation at line 9:
result
, last
and num_chars
.result
is being assigned as the final integer (and end result or destination of this script - - an integer) last
contains the string of the last line of the text file, distinguished at line 6num_chars
is the integer count of the number of characters in the last lineWhy is the number of characters from the last line not printing?
For my personal future reference, I’m working on Jose Portilla’s public GitHub repo for his open course on Udemy at this specific module: Python-Narrative-Journey/02-Field-Readiness-Exam-1/01-Field-Readiness-Exam-One.ipynb