0
Intermediate Python: Title Encoder .
A file is given with titles of books in it. I'm expected to print the combination of the 1st letters of the words on the same line but the titles in the book are already on separate lines. Help please...
9 odpowiedzi
+ 4
Okey!
You can first use file.readlines() to read the lines in the file to items in a list. Then for every item in the list you use split to split the strings to lists. Then use pick out every first letter and put them together. Use a for loop to go through the list. And file is your file of course.
myfile.readlines() => [tile1, title2,..]
print(title1)
>> Asdf jujj oki
Split title1 => wdLst = title1.split()
=> [Asdf’, ’jujj’, ’oki’]
Pick every first letter:
res = ’’
for i in wdLst:
res += wdLst[i][0]
print(res)
>> Ajo
Etc ...
Obs! Pseudo code! You have to translate it into Python. Take one step at a time!
+ 1
It is a good start to explaine it in english, but with code it become more easy to understand how to help you.
So the file contains one title per line? file f = ’Asdf jujj oki\nWer hygg\nGrujj hxg ugg’
When printing the three titles:
’Asdf jujj oki’
’Wer hygg’
’Grujj hxg ugg’
Should give this combinnation => ’AWG’ ?
Or how do you mean?
+ 1
a = "Yvonne Nelson\nBerla Monde\nNikki Samonas"
b = a.split('\n')
print(b)
c = b[0].split()
print(c)
res = ""
for wd in c:
res += wd[0]
print(res)
0
No, I should be printing out
"Ajo"
"Wh"
"Ghu"
0
This is what I'm arriving at but I want to print then in separate lines as in.
"YN"
"BM"
"NS"
https://code.sololearn.com/cqCfvvhSNN51/?ref=app
0
When I use the readlines(), it denies me from using the split
For eg:
msg = file.readlines()
info = msg.split()
Error saying list doesn't have an attribute split
0
titleLst = myfile.readlines() creates a list. The list contain your titles. You have to use split in the list items: titleLst[i].split(), where i is the i:th title in the list.
titleLst[0].split() is the same as ’Asdf jujj oki’.split()
and give you a new list [’Asdf’, ’jujj’, ’oki’]
0
The same error
AttributeError: 'list' object has no attribute 'split'
0
Yes, because lists are the result when you use split. You should use split on the strings inside the list.
Lst = [title0, title1, title2, ....]
title_0 = Lst[0]
title_1 = Lst[1]
For example title_0 is a string with three words: ”Asdf jujj oki”
This string object is okey to use split on:
wdLst = ”Asdf jujj oki”.split()
The result become a new list: [’Asdf’, ’jujj’, ’oki’]