Skip to content

Instantly share code, notes, and snippets.

@jakebox
Created December 18, 2021 16:16
Show Gist options
  • Save jakebox/8cd0006862363a3d4ceda23576844f4b to your computer and use it in GitHub Desktop.
Save jakebox/8cd0006862363a3d4ceda23576844f4b to your computer and use it in GitHub Desktop.
Program written to analyze character line counts in Hamlet.
import matplotlib.pyplot as plt
scene_file = "scene_iv.txt"
# Character: number of lines spoken
characters = {"LORD POLONIUS": 0, "QUEEN GERTRUDE": 0, "HAMLET": 0}
def count_characters_lines():
last_character = ""
with open(scene_file) as file: # Use file to refer to the file object
text = file.read().splitlines()
for line in text:
if line in characters: # e.g. line is "HAMLET"
last_character = line # Beginning of a chunk of of lines
elif last_character in characters: # The first time thru we get a bogus last_character
# If it's not a new speaker add one to the speaker's line tally
characters[last_character] += 1
def plot():
D = characters
plt.bar(*zip(*D.items()))
plt.show()
if __name__ == "__main__":
count_characters_lines()
print(characters)
print("Hamlet has", str((characters["HAMLET"] / characters["QUEEN GERTRUDE"]))[0:4] + "x more lines than Getrude")
plot()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment