Skip to content

Instantly share code, notes, and snippets.

@CodeByAidan
Last active April 15, 2024 20:19
Show Gist options
  • Save CodeByAidan/365694ac4c76e71fabcd1ade7aa917e0 to your computer and use it in GitHub Desktop.
Save CodeByAidan/365694ac4c76e71fabcd1ade7aa917e0 to your computer and use it in GitHub Desktop.
Wordwrap text to a specified line length. Takes a string or file-like object as input and returns the wrapped text.
"""
Wordwrap text to a specified line length.
Takes a string or file-like object as input and returns the wrapped text.
"""
import re
from typing import IO, Union
def wordwrap(text_or_file: Union[str, IO], max_line_length: int = 80) -> str:
"""
Wrap text to a specified line length.
Args:
text_or_file: The input text or file to wrap.
max_line_length: The maximum length of each line.
Returns:
str: The wrapped text.
Raises:
TypeError: If input is not a string or file-like object.
ValueError: If no matches are found after wrapping.
"""
if isinstance(text_or_file, str):
text = text_or_file
elif hasattr(text_or_file, "read"):
text = text_or_file.read()
else:
raise TypeError("Input must be either a string or a file-like object")
regexp = re.compile(
f"^$|.{{1,{max_line_length}}}$|.{{1,{max_line_length}}}", re.MULTILINE
)
if matches := regexp.findall(text):
return "\n".join(matches)
raise ValueError("Unexpectedly no matches")
INPUT_STR = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
WRAPPED_TEXT = wordwrap(INPUT_STR, max_line_length=80)
print(WRAPPED_TEXT)
FILE_PATH = "helloworld.bf"
with open(FILE_PATH, "r", encoding="utf-8") as file:
WRAPPED_TEXT = wordwrap(file, max_line_length=80)
print(WRAPPED_TEXT)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment