Last active
December 12, 2023 14:17
-
-
Save ypresto/c0b44be2a576a74d2f2b2680f15e251e to your computer and use it in GitHub Desktop.
Python: BudouXで指定した幅を目安に改行する (改行後が2文字以内にならないよう調整)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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