简体   繁体   中英

How to print list elements until a certain element is reached

I'm a python beginner trying to write a program that prints out each line of a TV pilot (txt file) if that line is dialogue.

A character name will always immediately proceed a block of dialogue (which can be one or more lines). And there will always be a blank line indicating the end of a block of dialogue. I have each line of the script as an element of script_list. I have all the character names as elements of character_list. There may be a better way to solve this, but right now I am trying to find a python command that recognizes when an element of script_list is a character name, and then prints the subsequent elements of script_list until it reaches a blank line.

As an example, for the following script I would want to only print: 'Looks like she's late again.', and then print every line of Bob's dialogue.

ACT I

INT. OFFICE CONFERENCE ROOM - MORNING

Bob and John stare at each other uncomfortably. <-- Not dialogue.

BOB Looks like she's late again. <-- Dialogue immediately proceeded by speaking character.

John glances at his watch.

JOHN [block of text that is multiple lines long]

Sarah enters the room.

I think you want something like:

if any(line.startswith(name) for name in character_list):

This will be True if the line starts any of the names from your list. This assumes that your list is all uppercase, otherwise you will match the "stage directions", which also start with names.

You could set a dialogue = True flag, then reset it when you reach a blank line.

Just to start you off here:

characterNames = ["JOHN", "BOB", "SARAH"]
play = ["These are stage directions", "BOB This is printed", "This is case sensitive, Sarah"]

for line in play:
    for name in characterNames:
        if name in line:
            print(line)

Note that this this assumes you aren't using full-caps within the dialogue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM