My text file structure is like this (lines reduced in length to one word for simplicity). Some verses contain colons which is why I don’t split on colons. The text file is called, “Psalms.txt”
1#1|Blessed…
1#2|But…
1#3|And…
1#4|The…
2#1|Why …
2#2|The…
2#3|Let…
2#4|He…
3#1|Lord…
The leftmost number on each line is the chapter number (chapter 1, 2, 3 etc all the way up to 150)
The number after the # is the verse number (a chapter may have a few verses or it may have over 100 verses).
The text after the | is the actual verse which might be say 10 words long or might be twice that length).
Note that I thought I needed 2 different characters to separate the data on - hence the # and the |
Please let me know if this is OK.
This is what the dictionary structure should look like:-
psalms = {
1: {1: 'Blessed...', 2: 'But...', 3: 'And...', 4: 'The...'}, 2: {1: 'Why...', 2: 'The...', 3: 'Let...', 4: 'He...'}, 3: {1: 'Lord...'} }
I have tried for 4 days to do this. I have watched YouTube vids, I have read webpages.
I have tried
chapter_number = 0
verse_number = 0
verse = ''
verse_dictionary = {verse_number: verse }
Psalms = {chapter_number : verse_dictionary }
counter =1
filename = 'Psalms.bak'
with open(filename) as f:
for line in f:
key,value = line.strip().split("|")
verse_dictionary[verse_number] = verse
print(verse_dictionary)
Psalms[chapter_number] = verse_dictionary
#print(Psalms[150][6])
I have tried:-
chapter_number = 0
verse_number = 0
verse = ''
verse_dictionary = {verse_number: verse }
Psalms = {chapter_number : verse_dictionary }
counter =1
filename = 'Psalms.txt'
with open(filename) as f:
for line in f:
split_line = line.split("|")
chapter_number = split_line[0].strip()
chapter_number = int(chapter_number)
verse_number = split_line[1].strip()
verse = split_line[2].strip()
print(chapter_number)
print(verse_number)
print(verse)
#print(chapter_number,verse_number,verse) # print it in any order
# data type chapter_number:int, verse_number:str, verse:str
verse_dictionary[verse_number] = verse
#print(verse_dictionary)
Psalms[chapter_number] = verse_dictionary
#print(Psalms[150][6])
Please would someone tell me how to read in the file and put the data into a nested dictionary?