+ 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.
9 ответов
+ 1
Take a look at this:
https://code.sololearn.com/c0H6zTQH4Ebu/?ref=app
+ 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.
+ 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.
+ 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")
0
I semi-understand what you two are saying, could you give me an example? My head hurts now lol
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.
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")
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")
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")