Skip to content

Instantly share code, notes, and snippets.

@ypresto
Last active December 12, 2023 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ypresto/c0b44be2a576a74d2f2b2680f15e251e to your computer and use it in GitHub Desktop.
Save ypresto/c0b44be2a576a74d2f2b2680f15e251e to your computer and use it in GitHub Desktop.
Python: BudouXで指定した幅を目安に改行する (改行後が2文字以内にならないよう調整)
import budoux
parser = budoux.load_default_japanese_parser()
def wrap_text(text: str, least_width: int):
phrases = parser.parse(text)
lines = ['']
for phrase in phrases:
if len(lines) > 0 and len(lines[-1]) >= least_width:
lines.append('')
lines[-1] += phrase
# merge last line if it is too short
if len(lines) >= 2 and len(lines[-1]) <= 2:
last_line = lines.pop()
lines[-1] += last_line
return '\n'.join(lines)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment