+ 1
Title encoder
file = open("/usercode/files/books.txt", "r", "a") lines = file.readlines() for line in lines: line_list = line.split(" ") nickname = [] for word in line_list: nickname.append(word[0], end="") file.write(nickname) can someone tell me whatâs wrong with this? cheers file.close()
8 Answers
+ 3
the task seems to be from *intermediate python* exercise 37.2 book club
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.
To count the number of words in a given string, you can use the split() function, or, alternatively, count the number of spaces (for example, if a string contains 2 spaces, then it contains 3 words).
+ 2
What is the task? Can you post description?
+ 2
file = open("/usercode/files/books.txt", "r", "a") # error
here if you are trying to open read and write use 'r+' or 'a' or 'r'. Need only one argument for mode.
file = open("/usercode/files/books.txt", "r+")
# file.write(nickname)
Task is to output in needed farmat. But you are writing to file..?
Output in needed format and len(nickname) instead of list...
Hope it helps..
+ 2
Oliver Clayden ,
see the comments:
file = open("/usercode/files/books.txt", "r") # use only filemode "r"
lines = file.readlines()
ndx = 1 # we need a counter for the line numbers
for line in lines:
line_list = line.split(" ")
num_words = len(line_list)
print(f"Line {ndx}: {num_words} words")
print(" .... ") # this should create the required output, please rework this line
ndx += 1 # increment the line counter
#nickname = [] # what is this ????
#for word in line_list:
#nickname.append(word[0], end="") # what is this ???
#file.write(nickname) # why do you want to write to the file?
file.close()
+ 2
file = open("/usercode/files/books.txt", "r", encoding = âUTF-8â)
# your code goes here
var = file.readlines()
for name in var:
l = list(name.split(' '))
s = ""
for i in l:
s += i[0]
print(s)
file.close()
This is my code. Look at the first line file canât have two opening modes. After second comma sometimes we write encoding of our file. I recomend to write encoding.
I like utf-8. And whatâs about you?
+ 1
Oliver Clayden
Apart from already mentioned error,
nickname.append(word[0]) #end="") Remove this second argument
And after loop, just print the list in a string form by using join() method..
print("".join(nickname))
Hope it helps..
0
You are given a file named "books.txt" with book titles, each on a separate line.
To encode the book titles you need to take the first letters of each word in the title and combine them.
For example, for the book title "Game of Thrones" the encoded version should be "GoT".
Complete the program to read the book title from the file and output the encoded versions, each on a new line.
0
this is the task i need to do