An acrostic poem is a form of writing where the first letter or word of each line spells out a hidden message. In this guide, we will implement a Python function to decrypt such poems. The goal is to extract the first word of every sentence (delimited by commas or periods) and concatenate them to reveal the hidden string.
We will use Python's built-in re (Regular Expression) library to handle the text splitting efficiently.
Understanding the Algorithm
To decrypt the message based on the specific rules of this challenge, we need to perform the following operations:
- Validation: Ensure the input is valid. If the poem is empty or
None, the function should returnNone. - Splitting: The text serves as a stream of sentences separated by punctuation. We need to split the string wherever a comma (
,) or a period (.) occurs. - Extraction: From every resulting segment (line), we strip whitespace and extract the first word.
- Concatenation: Join these words together to form the final result.
Step-by-Step Implementation
Handling Edge Cases
First, we must ensure the function handles empty inputs gracefully using a guard clause.
from typing import Optional
def acrostic_poetry_decryption(poem: str) -> Optional[str]:
if not poem:
return NoneSplitting with Regex
We use re.split(r"[,.]", poem) to break the text into chunks.
import re
text = "Rain is falling, It falls."
lines = re.split(r"[,.]", text)
print(f"Split lines: {lines}")Output:
Split lines: ['Rain is falling', ' It falls', '']Extracting and Joining
We iterate through the split lines, strip leading/trailing whitespace, and take the first token (word).
words = [line.strip().split(" ")[0] for line in lines if line.strip()] Complete Code Solution
Here is the complete, runnable script. It includes the acrostic_poetry_decryption function and a test block to verify the output.
import re
from typing import Optional
def acrostic_poetry_decryption(poem: str) -> Optional[str]:
"""
Decipher the message in the acrostic poem by extracting the first words
of each line (split by ',' or '.') and linking them together.
"""
if not poem:
return None
lines = re.split(r"[,.]", poem)
words = [line.strip().split(" ")[0] for line in lines]
decryption_text = "".join(words)
return decryption_text
if __name__ == "__main__":
string = "Rain is falling all around, It falls on field and tree. It rains on the umbrella here, And on the ships at sea."
result = acrostic_poetry_decryption(string)
print(f"Original Text: {string}")
print(f"Decrypted: {result}")Output:
Original Text: Rain is falling all around, It falls on field and tree. It rains on the umbrella here, And on the ships at sea.
Decrypted: RainItItAndConclusion
By combining Python's re module with list comprehensions, you can efficiently parse and transform unstructured text.
re.split(r"[,.]", text)breaks the text on multiple delimiters.str.strip()cleans up the noise around the data.str.split(" ")[0]isolates the target data (the first word).
This approach provides a robust way to uncover hidden messages in acrostic strings.