2011-07-12 105 views
0

这是我的困境:我正在用Python编写一个应用程序,它将允许我搜索平面文件(KJV bible.txt )为特定的字符串,并返回搜索的行号,书籍和字符串。但是,我还想返回找到该字符串的章节和诗句。这就要求我走到这条线的开头,并获得章节和诗句的编号。我是一名Python初学者,目前我仍在阅读Guido van Rossum的Python教程。这是我想为圣经学习小组完成的事情;几乎可以在任何地方运行cmd模块的东西。我感谢任何帮助......谢谢。下面是从圣经章节的示例的摘录:我如何从一行文本的开头获取数字,将它们分开并将它们打印出来

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. 

说我搜索“雅敬”和搜索结果中的一个是上面的第一道防线。我想去这行前面的数字(在这种情况下是1:1),并获得章节(1)和诗歌(1)并将它们打印到屏幕上。

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. 

代码:

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 
+1

如果你希望你的应用程序是可移植的,那么你可能想从程序中创建一个可执行文件,这样就不必安装python来运行它。看看这个[链接](http://www.py2exe.org/index.cgi/Tutorial)一个简单的方法来完成这个。 –

+0

@SC鬼 - 谢谢...是的,目前我使用py2exe。 – suffa

回答

1

使用regular expressionr'(\d+)\.(\d+)'

发现第2组比赛(match = re.match(r'(\d+)\.(\d+)', line)),你可以找到在第1组(chapter = match.group(1))的章节和诗句后。使用此代码:

使用此代码:
for ln, line in enumerate(book): 
     match = match = re.match(r'(\d+)\.(\d+)', line) 
     if match: 
      chapter, verse = match.group(1), match.group(2) 

     if word_search in line: 
      ... 
      print 'Book %s %s:%s ...%s...' % (book, chapter, verse, line) 
+0

我加了我的代码,看看我会在哪里实现这个... – suffa

+0

在'if word_search'之前。在这种情况下,您需要检查'match'是否为'None',并记住全局变量中的值,以便在读取文本时更新它们。 –

+0

我以为我明白了,但是你能告诉我我的代码出错了吗? – suffa

5

对空格执行一次拆分,然后拆分为:

passage, text = line.split(None, 1) 
chapter, verse = passage.split(':') 
+0

我添加了代码...在我的搜索结果后,如何返回查找数字? – suffa

+0

这是我得到Traceback(最近调用最后一个)的回溯错误: 文件“C:\ SQA_log \ biblebooks.py”,第26行, chapter,verse = passage.split(':') ValueError:需要多个值才能解包 – suffa

+0

然后,您可能会在行首有空白。 '... = line.lstrip()。split(None,1)' –

相关问题