Skip to content

Instantly share code, notes, and snippets.

@jackmaney
Created March 9, 2015 13:24
Show Gist options
  • Save jackmaney/5356eade0e46cdda012e to your computer and use it in GitHub Desktop.
Save jackmaney/5356eade0e46cdda012e to your computer and use it in GitHub Desktop.
r/dailyprogrammer challenge #204 [Easy]
# Daily Programming Challenge:
# http://www.reddit.com/r/dailyprogrammer/comments/2xoxum/20150302_challenge_204_easy_remembering_your_lines/
import requests
import re
import sys
macbeth = requests.get(
"https://gist.githubusercontent.com/Quackmatic/f8deb2b64dd07ea0985d/raw/macbeth.txt").text
# act_number: {scene: {description: (desc_of_scene), dialogues: [{speaker:
# S, text: T}]}}
play = {}
act_re = re.compile("^ACT\s+([A-Z]+)\.$")
scene_re = re.compile("^SCENE\s+([A-Z]+)\.\s+([^.]+).$")
character_re = re.compile("^([A-Z]+(?:\s+[A-Z]+)*)\.$")
act = None
scene = None
scene_desc = None
character = None
text = None
for line in macbeth.split("\n"):
line = line.strip()
act_match = act_re.match(line)
scene_match = scene_re.match(line)
character_match = character_re.match(line)
text = None
if act_match:
act = act_match.group(1)
elif scene_match:
scene = scene_match.group(1)
scene_desc = scene_match.group(2)
elif character_match:
character = character_match.group(1)
elif not line or line.startswith("["):
continue
else:
text = line
if text and act and scene and scene_desc and character:
if act not in play:
play[act] = {scene: {"description": scene_desc,
"dialogues": [{"speaker": character, "text": text}]}}
elif scene not in play[act]:
play[act][scene] = {
"description": scene_desc, "dialogues": [{"speaker": character, "text": text}]}
else:
most_recent_dialogue = play[act][scene]["dialogues"][-1]
if character == most_recent_dialogue["speaker"]:
play[act][scene][
"dialogues"][-1]["text"] = most_recent_dialogue["text"] + "\n" + text
else:
play[act][scene]["dialogues"].append(
{"speaker": character, "text": text})
phrase = " ".join(sys.argv[1:])
for act in play:
for scene in play[act]:
for dialogue in play[act][scene]["dialogues"]:
if phrase in dialogue["text"]:
print "Act {}".format(act)
print "Scene {} ({})".format(scene, play[act][scene]["description"])
print "Characters in scene: {}".format(
",".join(
sorted(list({x["speaker"] for x in play[act][scene]["dialogues"]}))))
print "Spoken by {}:".format(dialogue["speaker"])
print dialogue["text"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment