Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save rohan-paul/73ccbdbb7ddd6a089d0d0abc0374a629 to your computer and use it in GitHub Desktop.
Save rohan-paul/73ccbdbb7ddd6a089d0d0abc0374a629 to your computer and use it in GitHub Desktop.
import random
import textwrap
import torch # You missed importing the torch module.
device = 'cuda' if torch.cuda.is_available() else 'cpu'
import textwrap
def text_wrapper(text, width=90):
# Wraps the input text to the specified width
# Check for null, empty, or non-string input
if not text or not isinstance(text, str):
return text
# Validate and handle invalid width
if not isinstance(width, int) or width <= 0:
raise ValueError("Width must be a positive integer.")
wrapped_lines = []
# splits the input text into a list of lines based on newline chars
# To ensures that existing paragraph or line breaks in
# the input text are preserved.
for line in text.split('\n'):
# Preserve indentation: i.e. detects and preserves any
# leading whitespace (indentation) in each line,
# applying it to wrapped lines as well.
leading_spaces = len(line) - len(line.lstrip(' '))
indentation = ' ' * leading_spaces
# Wrap each line and add indentation to each subsequent line
wrapped_line = textwrap.fill(line, width=width,
subsequent_indent=indentation)
# textwrap.fill() wraps each line to the specified width.
# If a line is longer than width, it's broken into shorter lines,
# ensuring that no line exceeds the specified width.
# Words are not broken across lines; instead,
# the breaking occurs at whitespace.
wrapped_lines.append(wrapped_line)
# Finally, rejoin the individually wrapped lines into a single string,
# separating them with newline characters.
# This maintains the paragraph structure of the original text.
return '\n'.join(wrapped_lines)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment