擅长:python、mysql、java
<p>最后我重写了<code>textwrap</code>的一部分,在它分割字符串后对单词进行编码。在</p>
<p>与Tom的解决方案不同,Python代码不需要遍历每个字符。在</p>
<pre><code>def byteTextWrap(text, size, break_long_words=True):
"""Similar to textwrap.wrap(), but considers the size of strings (in bytes)
instead of their length (in characters)."""
try:
words = textwrap.TextWrapper()._split_chunks(text)
except AttributeError: # Python 2
words = textwrap.TextWrapper()._split(text)
words.reverse() # use it as a stack
if sys.version_info[0] >= 3:
words = [w.encode() for w in words]
lines = [b'']
while words:
word = words.pop(-1)
if len(word) > size:
words.append(word[size:])
word = word[0:size]
if len(lines[-1]) + len(word) <= size:
lines[-1] += word
else:
lines.append(word)
if sys.version_info[0] >= 3:
return [l.decode() for l in lines]
else:
return lines
</code></pre>