+ 1
Working with Files: Intermediate Python
"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." I managed to found how many words each title contains, but I am having a trouble in identifying the lines in the format above. Here is my try: "with open("/usercode/files/books.txt") as f: cont = f.readlines() for line in cont: words = line.split() for line in list(cont): print('Line ' + str(cont.index(line)) + ': ' + str(len(words)) + ' words')" Can anybody help me? Thanks in advance
4 odpowiedzi
+ 5
Or maybe better with the enumerate() function:
with open("/usercode/files/books.txt") as f:
cont = f.readlines()
for n, line in enumerate(cont):
words = line.split()
print('Line ' + str(n+1) + ': ' + str(len(words)) + ' words')
+ 2
What is the 2. loop for?
Maybe this is working as expected?
with open("/usercode/files/books.txt") as f:
cont = f.readlines()
n = 0
for line in cont:
words = line.split()
n += 1
print('Line ' + str(n) + ': ' + str(len(words)) + ' words')
+ 1
It worked!! Finally, I understood
Thank you for your help :)
0
You're welcome.