Retrieve block of text from a file, using key-words as start-point in Python 2.7?
Question: I'm trying to read a paragraph of text from a file based on the paragraph's
title (first line). For example, let's say the file is as so:

    
    
    Paragraph 1:1
    This paragraph 1. This paragraph 1. This paragraph 1. This paragraph 1. This  
    paragraph 1. This paragraph 1. This paragraph 1. This paragraph 1. This paragraph 
    1. This paragraph 1. This paragraph 1. This paragraph 1. This paragraph 1. This 
    paragraph 1. This paragraph 1. This paragraph 1. This paragraph 1. This paragraph 
    
    Paragraph 1:2
    This is paragraph 2. This is paragraph 2. This is paragraph 2. This is paragraph 
    2. This is paragraph 2. This is paragraph 2. This is paragraph 2. This is paragraph 
    2. This is paragraph 2. This is paragraph 2. This is paragraph 2. This is paragraph 
    2. This is paragraph 2. This is paragraph 2. This is paragraph 2. This is paragraph 2  
    

I have my code so that I can choose a title at random:

    
    
    def get_paragraph():
        f = open('file.txt','r')
        n = [str(x) for x in range(3)]
        paragraph_list = []
    
        for line in f:
            for numbers in n: # I know the following code isn't very pretty...
                if (number in line) and (':' in line) and (len(line) < 20):
                    paragraph_list.append(line)
    
        selection = random.choice(paragraph_list)
        print(selection)
    
    get_paragraph()  
    

Now, I want to be able to read the rest of the paragraph associated with that
first line, ending at the blank line - so that the output will be a randomly
selected paragraph from the file.

Any suggestions or help would be greatly appreciated!


Answer: I would approach this differently

from collections import defaultdict

    
    
    def get_paragraph(file_path)
    
        myString = open(file_path.read()
        paragraphList = myString.split('\n\n') # split by adjacent newlines
        paragraphList = [paragraph.split('\n') for paragraph in paragraphList]
        paragrpahDictionary = defaultdict(list)
        for paragraph in paragraphList:
            paragraphNumber = int(paragraph[0].split(:)[-1])
            paragraphBody = paragraph[1:]
            paragraphDictionary[paragraphNumber] = paragraphBody
    
       choices = paragraphDictionary.keys()
    
       theParagraph=random.choice(choices)
    
       for line in paragraphDictionary[theParagraph]
             print line + '\n'
    

