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!

Was it helpful?

Solution

You can use the str.split() method to split each paragraph item at the double \n (line break), then choose one at random.

One line:

paragraph = random.choice(open('file.txt').read().split('\n\n'))

OTHER TIPS

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'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top