+ 1

Working with files exercise

Working with Files You are given a books.txt file, which includes book titles, each on a separate line. Create a program to output how many words each title contains, in the following format: Line 1: 3 words Line 2: 5 words ... Make sure to match the above-mentioned format in the output. Code: with open("/usercode/files/books.txt") as f: #your code goes here I have no code to put here for you, I'm not even sure how to handle this. The exercise suggests using .split() but nowhere I try using it works. I've tried adjusting similar code: https://www.sololearn.com/Discuss/2564989/simpler-way-solved But couldn't quite tailor it to fit the exercise. Please help.

2nd Sep 2021, 4:32 PM
Kevin
9 odpowiedzi
2nd Sep 2021, 9:06 PM
Simon Sauter
Simon Sauter - avatar
+ 3
Kevin you can use the readlines function ,iterate over that and print each length of it.but you need to erase the newlines using strip function when getting the length so that it actually gets you the real count of words in book titles.
2nd Sep 2021, 4:49 PM
raynard
raynard - avatar
+ 2
Use "readlines" to get the lines, use a for loop to go through them. Use "split" to turn each line into a list of words. Then use "len" to get the number of words in the list.
2nd Sep 2021, 4:52 PM
Simon Sauter
Simon Sauter - avatar
+ 1
with open("/usercode/files/books.txt") as f: #your code goes here var = f.readlines() a=0 for i in var: a+=1 print("Line "+ "{}: ".format(a)+ str(len(i.split())) + " words")
20th Feb 2022, 10:39 PM
Liria
Liria - avatar
0
I semi-understand what you two are saying, could you give me an example? My head hurts now lol
2nd Sep 2021, 8:45 PM
Kevin
0
https://code.sololearn.com/cy2rdV0O6Eu5/?ref=app Kevin Bit of a mistake in my answer,but heres the code with the right answer,basically iterate over the variable that stores the readlines,then split to get a list with 2 seperate values,and get the length of that list.
3rd Sep 2021, 3:09 AM
raynard
raynard - avatar
0
with open("/usercode/files/books.txt") as f: #your code goes here words = f.readlines() for x in (range(len(words))): print("Line", str(x+1)+":", len(words[x].split()),"words")
9th Nov 2022, 1:08 PM
Laurent
0
Hi, i solved it this way: with open("/usercode/files/books.txt") as f: #your code goes here l=0 for line in f: l+=1 s=line.split(" ") w=len(s) print(f"Line {l}: {w} words")
13th Nov 2022, 11:12 AM
Sebastian Dötze
0
Check my code out ! with open("/usercode/files/books.txt") as f: #your code goes here l=0 for line in f: l+=1 x=line.split() y=len(x) print('Line'+" "+str(l)+":"+" "+str(y)+" "+"words")
2nd Dec 2023, 12:49 PM
vahid kamrani
vahid kamrani - avatar