Here is my dilemma: I’m writing an application in Python that will allow me to search a flat file (KJV bible.txt) for particular strings, and return the line number, book, and string searched for. However, I would also like to return the chapter and verse in which the string was found. That calls for me going to the beginning of the line and getting the chapter and verse number. I’m a Python neophyte, and am currently still reading through the Python tutorial by Guido van Rossum. This is something I’m trying to accomplish for a bible study group; something portable that can ran in the cmd module almost anywhere. I appreciate any help … Thanks. Below is an excerpt from an example of a Bible chapter:
Daniel
1:1 In the third year of the reign of Jehoiakim king of Judah came
Nebuchadnezzar king of Babylon unto Jerusalem, and besieged it.
Say I searched for ‘Jehoiakim’ and one of the search results was the first line above. I would like to go to the numbers that precede this line (in this case 1:1) and get the chapter (1) and verse (1) and print them to the screen.
1:2 And the Lord gave Jehoiakim king of Judah into his hand, with part
of the vessels of the house of God: which he carried into the land of
Shinar to the house of his god; and he brought the vessels into the
treasure house of his god.
Code:
import os
import sys
import re
word_search = raw_input(r'Enter a word to search: ')
book = open("KJV.txt", "r")
first_lines = {36: 'Genesis', 4812: 'Exodus', 8867: 'Leviticus', 11749: 'Numbers', 15718: 'Deuteronomy',
18909: 'Joshua', 21070: 'Judges', 23340: 'Ruth', 23651: 'I Samuel', 26641: 'II Samuel',
29094: 'I Kings', 31990: 'II Kings', 34706: 'I Chronicles', 37378: 'II Chronicles',
40502: 'Ezra', 41418: 'Nehemiah', 42710: 'Esther', 43352: 'Job', 45937: 'Psalms', 53537: 'Proverbs',
56015: 'Ecclesiastes', 56711: 'The Song of Solomon', 57076: 'Isaih', 61550: 'Jeremiah',
66480: 'Lamentations', 66961: 'Ezekiel', 71548: 'Daniel' }
for ln, line in enumerate(book):
if word_search in line:
first_line = max(l for l in first_lines if l < ln)
bibook = first_lines[first_line]
template = "\nLine: {0}\nString: {1}\nBook:\n"
output = template.format(ln, line, bibook)
print output
Use a regular expression:
r'(\d+)\.(\d+)'After finding a match (
match = re.match(r'(\d+)\.(\d+)', line)), you can find the chapter in group 1 (chapter = match.group(1)) and the verse in group 2.Use this code: