In @wrap_lines.py , function wrap, when there is a forbidden_starts punctuation immediately after an English or digit character, how to prevent line break in the middle of the English word or the number?
--- Content from referenced files ---
Content from @wrap_lines.py:
#!/usr/bin/env python3
import json
import os
import unicodedata
from opencc import OpenCC
from tqdm import tqdm
s2t = OpenCC("s2t")
t2jp = OpenCC("t2jp")
def s2jp(s: str) -> str:
s = s2t.convert(s)
s = t2jp.convert(s)
s = s.replace("嗯", "恩")
s = s.replace("篡", "竄")
return s
def get_char_width(char: str) -> int:
"""
Returns 2 for East Asian Wide characters (Chinese, etc.),
and 1 for others (English, ASCII).
"""
if unicodedata.east_asian_width(char) in ("F", "W", "A"):
return 2
return 1
def wrap(text: str, max_cn_chars: int = 33) -> list[str]:
"""
Wraps text preventing any punctuation (single or multiple)
from appearing at the start of a line.
Also prevents line breaks in the middle of English words or numbers.
"""
limit = max_cn_chars * 2
lines = []
current_line = ""
current_width = 0
code
Assistant
I will update wrap_lines.py to ensure that when a line wrap is forced by a forbidden_starts character (like a punctuation mark), any preceding English word or number is moved to the next line as a whole block, preventing it from being split.
Assistant
The wrap function in wrap_lines.py has been updated. Now, when a forbidden start character (like punctuation) forces a line break, the backtracking logic will move entire English words or numbers to the next line instead of splitting them character by character.
User
Assistant
The wrap_lines.py script has been updated. The wrapping logic now checks for both forbidden_starts at the beginning of the new line and forbidden_ends at the end of the current line, backtracking as necessary to ensure clean line breaks.
# Comprehensive list of characters that cannot start a line
# (Closing quotes, periods, commas, exclamation marks, etc.)
forbidden_starts = set(
')]}〕〉》」』】〙〗〟’”⦆»ヽヾーァィゥェォッャュョヮヵヶぁぃぅぇぉっゃゅょゎゕゖㇰㇱㇲㇳㇴㇵㇶㇷㇸㇹㇺㇻㇼㇽㇾㇿ々〻‐゠–〜?!‼⁇⁈⁉・、%,.:;。!?]):;=}¢°"†‡℃〆%,.'
)
i = 0
text_len = len(text)
while i < text_len:
char = text[i]
# Check for ASCII alphanumeric block (English word or number)
if ("a" <= char <= "z") or ("A" <= char <= "Z") or ("0" <= char <= "9"):
# Look ahead to find the end of the word/number
j = i + 1
while j < text_len:
c2 = text[j]
if ("a" <= c2 <= "z") or ("A" <= c2 <= "Z") or ("0" <= c2 <= "9"):
j += 1
else:
break
word = text[i:j]
word_width = len(word) # ASCII chars are width 1
# Check if the whole word fits
if current_width + word_width > limit:
if current_line:
# Wrap to next line
lines.append(current_line)
current_line = word
current_width = word_width
else:
# Word is longer than the line itself? Just add it.
current_line = word
current_width = word_width
else:
current_line += word
current_width += word_width
i = j
continue
char_w = get_char_width(char)
# 1. Check if adding the char exceeds limit
if current_width + char_w > limit:
# 2. Check: Is the character causing the break forbidden at the start?
if char in forbidden_starts:
# LOGIC: Recursive Backtracking
# We start a 'buffer' with the current char.
# We peel characters off the end of 'current_line' and add them
# to the START of the buffer until the buffer's first char is SAFE.
buffer = char
buffer_width = char_w
# Keep pulling back while:
# a) We have a previous line to pull from
# b) The thing currently at the start of our new line (buffer[0]) is forbidden
while current_line and (buffer[0] in forbidden_starts):
last_char = current_line[-1]
last_char_w = get_char_width(last_char)
# Remove from current line
current_line = current_line[:-1]
current_width -= last_char_w
# Add to start of buffer (new line)
buffer = last_char + buffer
buffer_width += last_char_w
# Now 'current_line' is the finished line, 'buffer' is the start of next line
lines.append(current_line)
# Reset for the next iteration
current_line = buffer
current_width = buffer_width
else:
# Standard break (char is safe to start line)
lines.append(current_line)
current_line = char
current_width = char_w
else:
# Fits in line
current_line += char
current_width += char_w
i += 1
if current_line:
lines.append(current_line)
return lines
filenames = os.listdir(jp_dir)
for filename in tqdm(filenames):
jp_path = f"{jp_dir}/{filename}"
zh_path = f"{zh_dir}/{filename}"
with open(jp_path, "r", encoding="utf-8") as f:
jp_data = json.load(f)
with open(zh_path, "r", encoding="utf-8") as f:
zh_data = json.load(f)
for jp_row, zh_row in zip(jp_data, zh_data):
if "name" in zh_row:
zh_row["name"] = s2jp(zh_row["name"])
zh_msg = zh_row["message"]
zh_msg = zh_msg.replace("\r", "")
zh_msg = zh_msg.replace("\n", "")
zh_msg = zh_msg.replace("[r]", "")
zh_msg = s2jp(zh_msg)
lines = wrap(zh_msg)
for i in range(len(lines) - 1):
lines[i] += "\r\n"
if lines and jp_row["message"].endswith("\r\n"):
# Weird behavior of VNTextPatch
lines[-1] += "[r]"
zh_msg = "".join(lines)
zh_row["message"] = zh_msg
with open(zh_path, "w", encoding="utf-8", newline="\n") as f:
json.dump(zh_data, f, ensure_ascii=False, indent=2)
if name == "main":
main()
--- End of content ---
Read @wrap_lines.py again. How to also prevent one or more forbidden_ends characters from appearing before any line break?
--- Content from referenced files ---
Content from @wrap_lines.py:
#!/usr/bin/env python3
import json
import os
import unicodedata
from opencc import OpenCC
from tqdm import tqdm
s2t = OpenCC("s2t")
t2jp = OpenCC("t2jp")
def s2jp(s: str) -> str:
s = s2t.convert(s)
s = t2jp.convert(s)
s = s.replace("嗯", "恩")
s = s.replace("篡", "竄")
return s
def get_char_width(char: str) -> int:
"""
Returns 2 for East Asian Wide characters (Chinese, etc.),
and 1 for others (English, ASCII).
"""
if unicodedata.east_asian_width(char) in ("F", "W", "A"):
return 2
return 1
def wrap(text: str, max_cn_chars: int = 33) -> list[str]:
"""
Wraps text preventing any punctuation (single or multiple)
from appearing at the start of a line.
Also prevents line breaks in the middle of English words or numbers.
"""
limit = max_cn_chars * 2
lines = []
current_line = ""
current_width = 0
code
forbidden_ends = set(
'([{〔〈《「『【〘〖〝‘“⦅«$—…‥〳〴〵\\[({£¥"々〇〉》」$⦆¥₩ #'
)
# Comprehensive list of characters that cannot start a line
# (Closing quotes, periods, commas, exclamation marks, etc.)
forbidden_starts = set(
')]}〕〉》」』】〙〗〟’”⦆»ヽヾーァィゥェォッャュョヮヵヶぁぃぅぇぉっゃゅょゎゕゖㇰㇱㇲㇳㇴㇵㇶㇷㇸㇹㇺㇻㇼㇽㇾㇿ々〻‐゠–〜?!‼⁇⁈⁉・、%,.:;。!?]):;=}¢°"†‡℃〆%,.'
)
i = 0
text_len = len(text)
while i < text_len:
char = text[i]
# Check for ASCII alphanumeric block (English word or number)
if ("a" <= char <= "z") or ("A" <= char <= "Z") or ("0" <= char <= "9"):
# Look ahead to find the end of the word/number
j = i + 1
while j < text_len:
c2 = text[j]
if ("a" <= c2 <= "z") or ("A" <= c2 <= "Z") or ("0" <= c2 <= "9"):
j += 1
else:
break
word = text[i:j]
word_width = len(word) # ASCII chars are width 1
# Check if the whole word fits
if current_width + word_width > limit:
if current_line:
# Wrap to next line
lines.append(current_line)
current_line = word
current_width = word_width
else:
# Word is longer than the line itself? Just add it.
current_line = word
current_width = word_width
else:
current_line += word
current_width += word_width
i = j
continue
char_w = get_char_width(char)
# 1. Check if adding the char exceeds limit
if current_width + char_w > limit:
# 2. Check: Is the character causing the break forbidden at the start?
if char in forbidden_starts:
# LOGIC: Recursive Backtracking
# We start a 'buffer' with the current char.
# We peel characters off the end of 'current_line' and add them
# to the START of the buffer until the buffer's first char is SAFE.
buffer = char
buffer_width = char_w
# Keep pulling back while:
# a) We have a previous line to pull from
# b) The thing currently at the start of our new line (buffer[0]) is forbidden
while current_line and (buffer[0] in forbidden_starts):
last_char = current_line[-1]
# Check if last_char is part of a word/number (ASCII alphanumeric)
# If so, move the WHOLE word to the buffer to prevent splitting it.
if (
("a" <= last_char <= "z")
or ("A" <= last_char <= "Z")
or ("0" <= last_char <= "9")
):
# Find the start of this word block in current_line
k = len(current_line) - 1
while k >= 0:
c = current_line[k]
if (
("a" <= c <= "z")
or ("A" <= c <= "Z")
or ("0" <= c <= "9")
):
k -= 1
else:
break
# k is index before the word
start_idx = k + 1
word_part = current_line[start_idx:]
current_line = current_line[:start_idx]
current_width -= len(word_part)
buffer = word_part + buffer
buffer_width += len(word_part)
else:
last_char_w = get_char_width(last_char)
# Remove from current line
current_line = current_line[:-1]
current_width -= last_char_w
# Add to start of buffer (new line)
buffer = last_char + buffer
buffer_width += last_char_w
# Now 'current_line' is the finished line, 'buffer' is the start of next line
lines.append(current_line)
# Reset for the next iteration
current_line = buffer
current_width = buffer_width
else:
# Standard break (char is safe to start line)
lines.append(current_line)
current_line = char
current_width = char_w
else:
# Fits in line
current_line += char
current_width += char_w
i += 1
if current_line:
lines.append(current_line)
return lines